题目
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].
翻译
给定一个n个元素的数组,所有元素向右移动k步。
思路
假设len为数组长度。
思路1,采用分部旋法,首先旋转0~len-k元素,然后在旋转len-k ~ 最后一个元素。最后将整个数组旋转。即可将所有元素向右旋转k个位置
思路2,暴力法,开辟一个数组,然后遍历当前数组,将第i个元素放置到 i+k%len 位置处。
代码
//思路1
class Solution {
public:
void rotate(vector<int>& nums, int k) {
if(k > nums.size()){
k = k % (nums.size());
}
std::reverse(nums.begin(),nums.end()-k);
std::reverse(nums.end()-k,nums.end());
std::reverse(nums.begin(),nums.end());
}
};

本文介绍了一种数组旋转算法,包括两种实现思路:一是通过分步旋转完成整体旋转;二是使用额外数组进行元素位置调整。适用于面试及日常编程需求。
900

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



