189. Rotate Array
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位,多出来的移到数组前面。
思路:
用一个新数组来替换它即可。
代码如下:
class Solution { public: void rotate(vector<int>& nums, int k) { if(k == 0 || nums.size() == 1 || nums.size() == 0) return; if(k > nums.size()) k = k % nums.size(); int i,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
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。