您好,登錄后才能下訂單哦!
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.
題目大意:
將數(shù)組中元素為0的元素放到數(shù)組的后面,但是數(shù)組中其他非0元素,保持原來(lái)的順序。
代碼如下:
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
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。