189. Rotate Array

Rotate an array ofnelements to the right byksteps.

For example, withn= 7 andk= 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位,多出来的移到数组前面。

思路:

用一个新数组来替换它即可。

代码如下:

classSolution{public:voidrotate(vector<int>&nums,intk){if(k==0||nums.size()==1||nums.size()==0)return;if(k>nums.size())k=k%nums.size();inti,count;count=0;i=nums.size()-k;vector<int>tmp;while(count!=nums.size()){if(i>=nums.size()){i-=nums.size();}tmp.push_back(nums[i]);i++;count++;}nums.swap(tmp);}};

2016-08-12 01:09:11