189. Rotate Array【easy】
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?
Related problem: Reverse Words in a String II
Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.
解法一:
1 class Solution { 2 public: 3 void rotate(vector<int>& nums, int k) { 4 int len = nums.size(); 5 6 if (len == 0 || k % len == 0) 7 { 8 return; 9 } 10 11 int mid = len - k % len; 12 13 reverseArray(nums, 0, mid - 1); 14 reverseArray(nums, mid, len - 1); 15 reverseArray(nums, 0, len - 1); 16 } 17 18 void reverseArray(vector<int>& nums, int start, int end) 19 { 20 int s = start; 21 int e = end; 22 23 while (s <= e) 24 { 25 int temp = nums[s]; 26 nums[s] = nums[e]; 27 nums[e] = temp; 28 s++; 29 e--; 30 } 31 } 32 };
注意:
1、边界值检查,避免对0取余和长度不合法
2、先分别翻转,再总体翻转,注意下标
解法二:
1 class Solution 2 { 3 public: 4 void rotate(int nums[], int n, int k) 5 { 6 k = k%n; 7 8 // Reverse the first n - k numbers. 9 // Index i (0 <= i < n - k) becomes n - k - i. 10 reverse(nums, nums + n - k); 11 12 // Reverse tha last k numbers. 13 // Index n - k + i (0 <= i < k) becomes n - i. 14 reverse(nums + n - k, nums + n); 15 16 // Reverse all the numbers. 17 // Index i (0 <= i < n - k) becomes n - (n - k - i) = i + k. 18 // Index n - k + i (0 <= i < k) becomes n - (n - i) = i. 19 reverse(nums, nums + n); 20 } 21 };
解法三:
1 public class Solution { 2 public void rotate(int[] nums, int k) { 3 k %= nums.length; 4 reverse(nums, 0, nums.length - 1); 5 reverse(nums, 0, k - 1); 6 reverse(nums, k, nums.length - 1); 7 } 8 public void reverse(int[] nums, int start, int end) { 9 while (start < end) { 10 int temp = nums[start]; 11 nums[start] = nums[end]; 12 nums[end] = temp; 13 start++; 14 end--; 15 } 16 } 17 }
先整体搞,再分开搞