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.
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:用一个额外的复制空间。 Time complexity: O(n). Space complexity: O(n)
解法2:翻转前n - k元素,翻转剩下的k个元素,最后翻转全部元素。O(n). Space complexity: O(1)
Java:
public void rotate(int[] nums, int k) { k %= nums.length; reverse(nums, 0, nums.length - 1); reverse(nums, 0, k - 1); reverse(nums, k, nums.length - 1); } public void reverse(int[] nums, int start, int end) { while (start < end) { int temp = nums[start]; nums[start] = nums[end]; nums[end] = temp; start++; end--; } }
Python:
class Solution: def rotate(self, nums, k): k %= len(nums) self.reverse(nums, 0, len(nums)) self.reverse(nums, 0, k) self.reverse(nums, k, len(nums)) def reverse(self, nums, start, end): while start < end: nums[start], nums[end - 1] = nums[end - 1], nums[start] start += 1 end -= 1
C++: Make an extra copy and then rotate. Time complexity: O(n). Space complexity: O(n).
class Solution { public: void rotate(int nums[], int n, int k) { if ((n == 0) || (k <= 0)) { return; } // Make a copy of nums vector<int> numsCopy(n); for (int i = 0; i < n; i++) { numsCopy[i] = nums[i]; } // Rotate the elements. for (int i = 0; i < n; i++) { nums[(i + k)%n] = numsCopy[i]; } } };
C++: Reverse the first n - k elements, the last k elements, and then all the n elements.
class Solution { public: void rotate(int nums[], int n, int k) { k = k%n; // Reverse the first n - k numbers. // Index i (0 <= i < n - k) becomes n - k - i. reverse(nums, nums + n - k); // Reverse tha last k numbers. // Index n - k + i (0 <= i < k) becomes n - i. reverse(nums + n - k, nums + n); // Reverse all the numbers. // Index i (0 <= i < n - k) becomes n - (n - k - i) = i + k. // Index n - k + i (0 <= i < k) becomes n - (n - i) = i. reverse(nums, nums + n); } };
类似题目: