题目:
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.
链接: https://leetcode.com/problems/rotate-array/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
void rotate(vector<int>& nums, int k) {
k = k%nums.size();
if(k==0||nums.size()<=1) return;
for(int i=0;i<k;i++){
nums.insert(nums.begin(), nums[nums.size()-1]);
nums.pop_back();
}
}
// from https://leetcode.com/discuss/27387/summary-of-c-solutions
void rotate2(vector<int>& nums, int k) {
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin()+k%nums.size());
reverse(nums.begin()+k%nums.size(), nums.end());
}
// from https://leetcode.com/discuss/28501/my-c-solution-o-n-time-%26%26-o-1-space
void rotate3(vector<int>& nums, int k) {
int n = nums.size();
if(n == 0) return;
k = k % n;
// initialize
int i = 0;
int nowIndex = 0;
int tmp = nums[0],stmp;
// exactly n steps, n times loop
for(int j = 0; j < n; j++){
// next index to exchange
nowIndex = (nowIndex + k)%n;
// exchange
stmp = nums[nowIndex];
nums[nowIndex] = tmp;
tmp = stmp;
// finish a circle,move to another circle
if(nowIndex == i){
nowIndex = ++i;
tmp = nums[nowIndex];
}
}
}
};