描述:数组元素个数为n,右移k位,如12345,右移3位后是34512
解答思路:将12345全旋转得到54321
将前3位旋转34521
将后两位旋转34512
处理核心是旋转reverse(vector<int> &nums,int begin,int end)
旋转分隔点是k=k%n (k是移动位数,n是数组长度)
class Solution {
public:
void reverse(vector<int>& num,int begin,int end){
int t=begin+(end-begin)/2;
int tmp=0;
int i=0;
while(begin<=t){
tmp=num.at(begin);
num.at(begin)=num.at(end-i);
num.at(end-i)=tmp;
begin++;
i++;
}
}
void rotate(vector<int>& nums, int k) {
int n=nums.size();
k=k%n;
if(n==2 && k==1 ){
int tmp=0;
tmp=nums.at(0);
nums.at(0)=nums.at(1);
nums.at(1)=tmp;
}else if(k==n ||k==0){
}else if(k<n){
reverse(nums,0,n-1);
reverse(nums,0,k-1);
reverse(nums,k,n-1);
}
}
};