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就移除并加在末尾,索引不变;不是就将索引后移
当索引达到数组总长度减掉0的个数减一的时候就代表都移完了。

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    var num = nums.length;
    var numOf0 = 0
    var i = 0;
    while (i<num-numOf0){
        if (nums[i]===0) {
            nums.splice(i,1);
            nums.push(0);
            numOf0++;
        } else {
            i++;
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容