您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。