解题思路:
对于字符串s,设s由字符串s1和s2两部分组成。先把s1逆序,再把s2逆序, 最后把s逆序,数组s就向右旋转了s2.size()个元素
问题描述:
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.
AC解,C++代码,菜鸟一个,请大家多多指正
class Solution {
public:
void reverse(vector<int>& nums, int left, int right) {
while (left < right) {
int tmp = nums[left];
nums[left] = nums[right];
nums[right] = tmp;
left++;
right--;
}
}
void rotate(vector<int>& nums, int k) {
int nums_length = nums.size();
if (nums_length < 2) {
return ;
}
k = k % nums_length;
if (k < 1) {
return ;
}
reverse(nums, 0, nums_length - 1 - k);
reverse(nums, nums_length - k, nums_length - 1);
reverse(nums, 0, nums_length - 1);
return ;
}
};