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]
.
Related problem: Reverse Words in a String II
限制为 (O(1)) extra space 的话, 相对有难度.
人家很帅屁的方法:
[1,2,3,4,5,6,7]
Original
[7,6,5,4,3,2,1]
A[0..n-1] reverse
[5,6,7,4,3,2,1]
A[0..k-1] reverse
[5,6,7,1,2,3,4]
A[k..n-1] reverse
按人家思路,自己写的代码:
void rotate(vector<int>& A, int k) {
int n = A.size();
k %= n;
if (n == 0 || n == 1 || k >= n) return;
reverse(A, 0, n - 1);
reverse(A, 0, k - 1);
reverse(A, k, n - 1);
}
void reverse(vector<int>& A, int start, int end) {
int temp;
//代码简洁明了
while (start < end) { //注意条件
temp = A[start];
A[start] = A[end];
A[end] = temp;
start++;
end--;
}
// start and end are the index based on 0
// 自己写的这个有些复杂并且还错了!!!
// int temp, n = end - start + 1;
// for (int i = start; i <= (n-1)/2; i++){
// temp = A[i];
// A[i] = A[n - (i + 1)];
// A[n - (i + 1)] = temp;
// }
}