原题链接:力扣
solution:
暴力做法:不满足空间复杂度O(1)
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n=nums.size();
vector<int> res(n);
for(int i=0,t=0;i<n;i++){
if(i+k+1>n) t=(i+k)%n;
else t=i+k;
res[t]=nums[i];
}
for(int i=0;i<n;i++) nums[i]=res[i];
}
};
双指针:reverse本质就是双指针
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
k %= n;
reverse(nums.begin(),nums.end());
reverse(nums.begin(),nums.begin()+k);
reverse(nums.begin()+k,nums.end());
}
};