Description: The number of array elements is n, the right shift K-bit, such as 12345, 3-bit right shift after 34512
Answer the idea: 12345 full rotation to get 54321
Rotate the top 3 bits 34521
Rotate the rear two bits 34512
Processing core is rotating reverse (vector<int> &nums,int begin,int end)
The rotation separator is k=k%n (k is the number of moving bits, n is the array length).
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);
}
}
};
Leetcode (2) array element right shift