Topic description

Given an array nums, write a function to move all 0s to the end of the array while maintaining the relative order of the non-zero elements.

Note that the array must be manipulated in-place without copying the array.

Example 1:

 输入: nums = [0,1,0,3,12]
输出: [1,3,12,0,0]

Example 2:

 输入: nums = [0]
输出: [0]
Likou original title address: https://leetcode.cn/problems/move-zeroes

Thought analysis

The solution is to traverse the number of occurrences of 0 and delete it, and finally append 0 to the end according to the number of occurrences of 0.

 var moveZeroes = function (nums) {
    let count = 0 // 1. 定义一个变量,用来统计0出现的次数
    for (let i = 0; i < nums.length; i++) { // 2. 遍历这个数组,看看0出现了几次
        if (nums[i] == 0) { // 3. 如果遇到的不是0,不做任何操作;如果遇到0了,就把0删掉
            nums.splice(i, 1) // 4. 把遇到的这一项(0)给删除掉
            i-- // 5. 注意 数组塌陷,索引统一往前平移一位
            count = count + 1 // 6. 然后统计一下0出现的次数
        }
    }
    for (let i = 0; i < count; i++) { // 7. 根据0出现的次数,决定往数组的尾部追加几个0
        nums.push(0) // 8. 出现了几个0,最后就追加几个0,
    }
};

In this way, we need to traverse twice, we can also solve it by traversing once, and the ideas are slightly similar. The following code

Add an end item identifier to the end of solution 2, and delete it when traversing encounters 0.

 var moveZeroes = function (nums) {
    nums.push('endFlag') // 1. 手动在数组的最后,追加一项,用于判断是否遍历到最后的标识
    for (let i = 0; i < nums.length; i++) { // 2. 遍历这个数组
        // 3. 一开始肯定不是最后一项的标识,所以继续往后看
        if (nums[i] == 'endFlag') { // 8. 当遇到之前我们手动添加的'endFlag'标识的时候,就说明原来的数组遍历一遍了
            nums.splice(i, 1) // 9. 最后再把之前手动添加的标识给删掉就行啦,搞定
            return
        }
        if (nums[i] === 0) { // 4. 当遇到0的时候做移动零操作
            nums[nums.length] = 0 // 5. 先再数组的最后的位置添加一个0
            nums.splice(i, 1) // 6. 然后在把当前的0删除掉,这样也可以理解为移动0
            i-- // 7. 注意数组删除掉一个元素以后,数组的索引塌陷,后续的索引都会往前进一位,所以需要再统一扣除1位,以达到平衡
        }
    }
};

Summarize

In actual work, the time complexity should be prioritized over the space complexity. Because of the space complexity problem, it is enough to add more memory. But time complexity is the speed goal we pursue when writing code. Therefore, if you can traverse once, it is best not to traverse twice. As for the definition of several variables, which leads to the use of some more memory, it can basically be ignored.


水冗水孚
1.1k 声望584 粉丝

每一个不曾起舞的日子,都是对生命的辜负