解法一 move to a new array
移动后的index可以用 (i+k)%len [i: current index; k: 移动的位数; len: size of the array]来计算出。
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int len = nums.size();
vector<int> res(len, 0);
for(int i=0;i<len;i++){
res[(i+k)%len] = nums[i];
}
nums = res;
}
};
解法二 no extra array
基本思想是用一个variable来记录上一个被覆盖的值
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int len = nums.size();
if (nums.empty() || (k %= len) == 0) return;
int idx=0, start=0, cur = 0, pre = nums[idx];
for(int i=0;i<len;i++){
int nidx = (idx+k)%len;
cur = nums[nidx];
nums[nidx] = pre;
pre = cur;
idx=nidx;
if(idx==start){
idx = ++start;
pre = nums[idx];
}
}
}
};
解法三 reverse
trick:reverse前半段,reverse后半段,reverse整个 ——> DONE
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int len = nums.size();
if (nums.empty() || (k %= len) == 0) return;
int n = (len-k)%len;
reverse(nums.begin(), nums.begin()+n);
reverse(nums.begin()+n, nums.end());
reverse(nums.begin(), nums.end());
}
};