题目名称
Rotate Array—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].
Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.
分析
题目的意思显而易见,就是循环右移数组中元素k次。要求我们用更多的方法来求解这道题,下面我将列出几种解题思路:
思路一: 考虑到移动的次数等于数组的长度时,数组会恢复成原来的顺序,所以先对k昨取余运算:k=k%nums.size(). 然后根据K,将数组中最后一个元素取出来放到数组头部,重复k次。
思路二: 对k取余后,将nums.end()之前的k个元素添加到数组头部,最后保持数组长度不变(删除多余元素)。
思路三: 对k取余后将整个vector逆转,再逆转前k个元素,再逆转后面的所有元素,这里要用到STL中的算法,所以需要添加头文件algorithm。如图所示:
C++代码
思路一:
void rotate1(vector<int>& nums, int k) {
k%=nums.size();
if(k==0 || nums.size()==0)
return;
for(int i=0;i<k;i++){
int temp = nums.back();
nums.insert(nums.begin(),temp);
nums.pop_back();
}
}
思路二:
void rotate2(vector<int>& nums, int k) {
k%=nums.size();
int length = nums.size();
if(k=0 || length==0)
return;
vector<int>::iterator iter1 = nums.end()-k;
nums.insert(nums.begin(),iter1,nums.end());
nums.resize(length);
}
思路三:
void rotate3(vector<int>& nums, int k) {
k%=nums.size();
if(k==0 || nums.size()==0)
return;
reverse(nums.begin(), nums.end());
reverse(nums.begin(), nums.begin()+k);
reverse(nums.begin()+k, nums.end());
}
总结
用多种方法解一道题,既锻炼思维,又增长能力,因为我本人目前能力有限,很多时候没有考虑到如何去优化算法,希望自己能够越来越努力,越来越强大!