LeetCode 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搬到陣列最後面,剩下的元素保持原本的排序。

範例:
nums = [0, 1, 0, 3, 12] ,執行後回傳[1, 3, 12, 0, 0]

注意:
只能在當前陣列中操作,不能用一個新的陣列來解。盡量減少操作次數。

思路

這題用到的技巧後面有不少題目一樣會用到,使用另外一個變數index來記錄碰到的非0數字,遇到非0整數,將整數塞到index的位子, 最後陣列長度扣除index就是0的數目,將陣列index之後的數字改為0就完成搬移的動作。

ex. nums = [0, 1, 0 , 3] , index = 0
nums[0] == 0, 跳過
nums[1] == 1, nums[0] = 1, index++;
nums[2] == 0, 跳過
nums[3] == 3, nums[1] = 3, index++;
結束後 nums = [1,3,0,3],接下來將nums後面的[0,3]用0取代

解題

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    var index = 0;
    for(var i = 0 ; i < nums.length ; i++){
        var n = nums[i]; 
        // not zero, index++, push to array
        if(n !== 0){
            nums[index++] = n;    
        }
    }

    // after index to zero
    for(index ; index < nums.length ; index++){
        nums[index] = 0;
    }
};

results matching ""

    No results matching ""