样例 1:输入: [1,2,3,4,5,6,7], k = 3输出: [5,6,7,1,2,3,4]解释:向右旋转1步: [7,1,2,3,4,5,6]向右旋转2步: [6,7,1,2,3,4,5]向右旋转3步: [5,6,7,1,2,3,4]样例 2:输入: [-1,-100,3,99], k = 2输出: [3,99,-1,-100]解释:向右旋转1步: [99,-1,-100,3]向右旋转2步: [3,99,-1,-100]
挑战
给出尽可能多的解决办法, 至少有三种方法可以解决这个问题.
能够用O(1)的时间复杂度解决问题吗?
public class Solution { /** * @param nums: an array * @param k: an integer * @return: rotate the array to the right by k steps */ public int[] rotate(int[] nums, int k) { // Write your code here k=k%nums.length; int[] temp=new int[nums.length-k]; System.arraycopy(nums, 0, temp, 0, temp.length); for (int i =temp.length; i < nums.length; i++) { nums[i-temp.length]=nums[i]; } System.arraycopy(temp, 0, nums, k, temp.length); return nums; }}