题目来源【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];
}
}
}
};

本文介绍了在LeetCode上解决数组旋转问题的两种方法。一种是通过往前插入元素实现旋转;另一种则是通过直接移动元素的方式完成旋转操作。这两种方法各有特点,能够帮助读者理解并掌握数组旋转的不同实现方式。
379

被折叠的 条评论
为什么被折叠?



