1.描述
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.
2.分析
方法一:直接计算下标,index = (i + k) % n,实现空间复杂度O(1)需要技巧。
方法二:翻转数组的前n-k个数,再翻转数组的后k个数,最后整个数组翻转。
方法三:翻转整个数组,再翻转前k个数,最后翻转数组后n-k个数。
3.代码
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if (nums.empty() || (k %= nums.size()) == 0) return;
int n = nums.size();
reverse(nums.begin(), nums.begin() + n - k);
reverse(nums.begin() + n - k, nums.end());
reverse(nums.begin(), nums.end());
}
};
网友评论