题目:
Given an array, rotate the array to the right by k steps, where k is non-negative.
思路:
- 旋转整个数组。
- 旋转nums[0~k-1]部分。
- 旋转nums[k-1~尾]部分。
代码实现:
class Solution {
public:
void rotate(vector<int>& nums, int begin, int end){
while (begin < end){
int t = nums[begin];
nums[begin] = nums[end];
nums[end] = t;
++begin;
--end;
}
}
void rotate(vector<int>& nums, int k) {
if (nums.size() <= 1){
return ;
}
k = k % nums.size();
rotate(nums, 0, nums.size()-1);
rotate(nums, 0, k-1);
rotate(nums, k, nums.size()-1);
}
};
参考:
https://leetcode.com/problems/rotate-array/discuss/54250/Easy-to-read-Java-solution