本文共 836 字,大约阅读时间需要 2 分钟。
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位,多出来的移到数组前面。
思路:
用一个新数组来替换它即可。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | 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); } }; |
转载地址:http://hmnbo.baihongyu.com/