问题描述
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
is rotated to [5,6,7,1,2,3,4]
.
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Hint:
Could you do it in-place with O(1) extra space?
Could you do it in-place with O(1) extra space?
算法
代码一
1 public void rotate(int[] nums, int k) { 2 int n = nums.length; 3 int temp; 4 k = k % n; 5 for (int i = 0; i < n / 2; i++) { 6 temp = nums[i]; 7 nums[i] = nums[n - 1 - i]; 8 nums[n - 1 - i] = temp; 9 } 10 for (int i = 0; i < k / 2; i++) { 11 temp = nums[i]; 12 nums[i] = nums[k - 1 - i]; 13 nums[k - 1 - i] = temp; 14 } 15 for (int i = 0; i < (n - k) / 2; i++) { 16 temp = nums[k + i]; 17 nums[k + i] = nums[n - 1 - i]; 18 nums[n - 1 - i] = temp; 19 } 20 }
注意k可能会比n大,所以将k模n。
代码二
1 public void rotate1(int[] nums,int k){ 2 int n=nums.length; 3 k=k%n; 4 reverse(nums,0,n-1); 5 reverse(nums,0,k-1); 6 reverse(nums,k,n-1); 7 } 8 private void reverse(int[] nums,int s,int e){ 9 int temp; 10 while(s<e){ 11 temp=nums[s]; 12 nums[s]=nums[e]; 13 nums[e]=temp; 14 s++; 15 e--; 16 } 17 } 18 private void reverse1(int[] nums,int m,int n){ 19 while(m<n){ 20 nums[m]^=nums[n]; 21 nums[n]^=nums[m]; 22 nums[m]^=nums[n]; 23 m++; 24 n--; 25 } 26 }
代码二的思想和代码一的思想一样,优点是把三次反转写成一个函数。另外两个值交换可以用异或运算。
代码三
1 //https://leetcode.com/discuss/28501/my-c-solution-o-n-time-%26%26-o-1-space 2 public void rotate2(int[] nums, int k) { 3 int n = nums.length; 4 k = k % n; 5 int i = 0; 6 int nowIndex = 0, tmp1, tmp2 = nums[0]; 7 for (int j = 0; j < n; j++) { 8 tmp1 = tmp2; 9 nowIndex = (nowIndex + k) % n; 10 tmp2 = nums[nowIndex]; 11 nums[nowIndex] = tmp1; 12 if (nowIndex == i && i < n - 1) { 13 i++; 14 nowIndex = i; 15 tmp2 = nums[nowIndex]; 16 } 17 18 } 19 }