189 Rotate Array
Rotate an array of n elements to the right by k steps.
For example,
with n = 7 and k = 3,
the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].
Solution1
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
if ( n == 0 ) return;
k = k%n;
reverse(nums.begin(), nums.begin() + n-k);
reverse(nums.begin() + n-k, nums.end());
reverse(nums.begin(), nums.end());
return;
}
};
Solution2
class Solution {
public:
int common(int n, int k) {
int i1 = max(n, k), i2 = min(n, k);
if ( i1%i2 == 0 ) return i2;
return ( common(i1-i2, i2) );
}
void rotate(vector<int>& nums, int k) {
int n = nums.size();
if ( n <= 1 or k%n == 0 ) return;
k = k%n;
int n0 = common(n, k);
for ( int i = 0; i <= n0-1; i++) {
int i0 = i, ilast = nums[i0], j = (i0+k)%n;
while ( j != i0 ) {
int tmp = nums[j];
nums[j] = ilast;
ilast = tmp;
j = (j+k)%n;
}
nums[i0] = ilast;
}
return;
}
};