题目来源【Leetcode】
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].
方法一:往前插入
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if(k != 0 && nums.size()!=0){
int i = 0;
while(i < k){
nums.insert(nums.begin(),nums[nums.size()-1]);
nums.pop_back();
i++;
}
}
}
};
方法二:直接进行移动:
class Solution {
public:
void rotate(vector<int>& nums, int k) {
int n = nums.size();
if(k > 0 && n !=0){
vector<int>temp(nums);
for(int i = 0; i < n; i++){
nums[(i+k)%n] = temp[i];
}
}
}
};