题目英文描述:
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
Could you do it in-place with O(1) extra space?
题目中文描述:
定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
说明:
尽可能想出更多的解决方案,至少有三种不同的方法可以解决这个问题。
要求使用空间复杂度为 O(1) 的 原地 算法。
代码(环状替换)(O(n))(效率比反转高):
class Solution {
public:
void rotate(vector<int>& nums, int k) {
k = k % nums.size();
int count = 0;
for(int start = 0; count < nums.size(); ++start) {
int cur = start;
int curv = nums[start];
do {
int next = (cur + k) % nums.size();
int temp = nums[next];
nums[next] = curv;
cur = next;
curv = temp;
++count;
}while(cur != start);
}
}
};
代码(反转)(O(n)):
class Solution {
public:
void rotate(vector<int>& nums, int k) {
k = k % nums.size();
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin() + k);
reverse(nums.begin() + k, nums.end());
}
};