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.
解题思路:
利用翻转的巧妙之处,
1 2 3 4 5 6 7
4 3 2 1 7 6 5
5 6 7 1 2 3 4
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if (nums.size() < k) k = k % nums.size();
rotate(nums, 0, nums.size() - k - 1);
rotate(nums, nums.size() - k, nums.size() - 1);
rotate(nums, 0, nums.size() - 1);
}
void rotate(vector<int>& nums, int start, int end) {
int i = start;
int j = end;
while (i < j) {
swap(nums[i++], nums[j--]);
}
}
};