https://leetcode.com/problems/rotate-array/description/
Solution 1. O(1) space, 3 reversions
void rotate(vector<int>& nums, int k) {
int N = nums.size();
if(N ==0 || k%N ==0) return;
k = k%N;
reverse(begin(nums), begin(nums)+N-k);
reverse(begin(nums)+N-k, end(nums));
reverse(begin(nums), end(nums));
}
Solution 2. O(1) space, keep rotating one by one until total number of rotating = nums.size()
void rotate1(vector<int>& nums, int k) {
int N = nums.size();
if(N ==0 || k%N ==0) return;
k = k%N;
int cnt = 0, iStart = 0, iCurrt = 0, numRot = nums[0], tmp;
while(cnt<N) {
do{
iCurrt = (iCurrt + k)%N;
tmp = nums[iCurrt];
nums[iCurrt] = numRot;
numRot = tmp;
cnt++;
}while(iStart != iCurrt);
iStart++;
iCurrt = iStart;
numRot = nums[iCurrt];
}
}
Solution 3.
void rotate(vector<int>& nums, int k) {
int N = nums.size();
k = k%N;
if(k == 0) return;
vector<int> nk(k);
for(int i=0; i<k; i++) nk[i] = nums[N-k+i];
for(int i=N-k-1; i>=0; i--) {
nums[i+k] = nums[i];
}
for(int i=0; i<k; i++) nums[i] = nk[i];
}
No comments:
Post a Comment