Rotate Array (Easy)

Description

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].

Analysis

这题类似编程之美上一题的思路。相当于翻转字符串。
以n - k为界,分别对数组的左右两边执行一次逆置;然后对整个数组执行逆置

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//C++
class Solution {

void rev(int nums[],int start,int end){
for(int i = 0;i<(end-start+1)/2;i++){
swap(nums[start+i],nums[end-i]);
}
}
public:
void rotate(int nums[], int n, int k) {
k = k%n;
if(k!=0){
rev(nums,0,n-k-1);
rev(nums,n-k,n-1);
rev(nums,0,n-1);
}
}
};