Move Zeroes
Given an array nums
, write a function to move all's to the 0
end of it while maintaining the relative order of the No N-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should is [1, 3, 12, 0, 0]
.
Note:
- You must does this in-place without making a copy of the array.
- Minimize The total number of operations.
https://leetcode.com/problems/move-zeroes/
Put all of the 0 in the array to the end, and you cannot simply open an array again.
The first elegant approach, open a variable count=0, the array of nonzero number, in order to move to the subscript count of the position, each move a count++, the last to fill 0;
1 /**2 * @param {number[]} nums3 * @return {void} does not return anything, modify Nums in-place instead.4 */5 varMovezeroes =function(nums) {6 varCount = 0;7 for(vari = 0; i < nums.length; i++){8 if(Nums[i]!== 0){9Nums[count] =Nums[i];Tencount++; One } A } - for(; count < nums.length; count++){ -Nums[count] = 0; the } -};
The second call to the powerful splice method, first record the position of the next 0, from the back to the 0 from the array to delete (from the trip will be disrupted subscript order), and finally completed.
1 /**2 * @param {number[]} nums3 * @return {void} does not return anything, modify Nums in-place instead.4 */5 varMovezeroes =function(nums) {6 varIndexarr =[], I;7 for(i = 0; i < nums.length; i++){8 if(Nums[i] = = = 0){9 Indexarr.push (i);Ten } One } A for(i = indexarr.length-1; I >= 0; i--){ -Nums.splice (Indexarr[i], 1); - } the for(i = 0; i < indexarr.length; i++){ -Nums.push (0); - } -};
[Leetcode] [JavaScript] Move Zeroes