题目

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

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

[show hint]

Related problem: Reverse Words in a String II

Credits:
Special thanks to @Freezen for adding this problem and creating all test cases.

大意

旋转数组

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int len =nums.size();
k = k%len;
reverse(nums,0,len-1);
reverse(nums,0,k-1);
reverse(nums,k,len-1);
return;
}
void reverse(vector<int>& nums,int left, int right)
{
int len = nums.size();
while(left<right)
{
swap(nums[left],nums[right]);
left++;
right--;
}
}

};

思路

很简单的一道题,但是毕竟第一次见。

三步反转法来做,时间复杂度是O(n),空间复杂度是O(1)

一共有3步。假设输入数组的下标是0~ n-1,需要rotate的步数是k.

step 1 reverse原来的数组

step 2 reverse 0~ k-1

step 3 reverse k ~ n-1