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.
Hint:
Could you do it in-place with O(1) extra space?
首先這道題到底是什麼意思?
從字面看,是通過K步來旋轉N個元素的數組。。。
但其實呢,是將一個數組跳過K個數到右邊,也就是將K個數移到開頭
- 思路1
在LEETCODE上不能通過 - -!
class Solution {
public:
vector<int> rotate(vector<int>& nums ,int k) {
if(k>nums.size())
k %= nums.size();
vector<int> v;
for(int i=nums.size()-k; i<nums.size(); i++)
v.push_back(nums[i]);
for(int i=0; i<nums.size()-k; i++)
v.push_back(nums[i]);
return v;
}
};
- 思路2
很清晰
class Solution {
public:
vector<int> rotate(vector<int>& nums ,int k) {
if(k>nums.size())
k %= nums.size();
reverse(nums.begin(),nums.end());
reverse(nums.begin(),nums.begin()+k);
reverse(nums.begin()+k,nums.end());
return nums;
}
};