283. Move Zeroes
這是leetCode第283題
題目
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:
1.You must do this in-place without making a copy of the array.
2.Minimize the total number of operations.
意思是說:
給一個數字數組,寫出一個函數把所有的0都移到數組的末尾,同時要保持非零的數字相對順序不變。
給個例子,給出數組[0,1,0,3,12],調用函數之后,數組應該是這個樣子的[1,3,12,0,0]。
注意:
1.你必須在原數組上操作,不能復制數組。
2.你的操作總數必須最小化
思路
1.先把所有非零數組都放在數組前面,并記錄非零數字的數量n
舉個例子:
給出數組 nums=[1,2,0,3,0,4] n=0表示非零數字數量
第一步:循環數組,當遇到非零數字時,nums[n]的位置賦值為該數字。
i = 0 nums=[1,2,0,3,0,4] 1仍然在原來的位置 n=>1
i = 1 nums=[1,2,0,3,0,4] 2仍然在原來的位置 n=>2
i = 2 nums=[1,2,0,3,0,4] 不變
i = 3 nums=[1,2,3,3,0,4] nums [n] =nums[ i ] n=>3
i = 4 nums=[1,2,3,3,0,4] 不變
i = 5 nums=[1,2,3,4,0,4] nums [n] =nums[ i ] n=>4
這樣,就將所有非零數字都放在了數組開頭。
2.將數組第n個位置之后的數字都重新賦值為0(因為非零數字都在n+1個位置之前);
最后得到結果:nums=[1,2,3,4,0,0]
代碼如下:
/**
* @param {number[]} nums
* @return {void}
*/
var moveZeroes = function (nums) {
var count =0;
var l = nums.length;
for(var i=0;i<l;i++){
if(nums[i]!==0){
nums[count++]=nums[i]
}
}
for(;count<l;count++){
nums[count]=0;
}
}