您好,登錄后才能下訂單哦!
283. Move Zeroes
Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
題目大意:
將數組中元素為0的元素放到數組的后面,但是數組中其他非0元素,保持原來的順序。
代碼如下:
class Solution { public: void moveZeroes(vector<int>& nums) { int step = 0; for(int i = 0 ; i < nums.size();i++) { if(nums[i] == 0) { step++; } else { nums[i - step] = nums[i]; if(step != 0) nums[i] = 0; } } } };
2016-08-12 01:26:32
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。