【LeetCode】数组初级算法-移动零

题目描述

移动零
给定一个数组 nums,编写一个函数将全部 0 移动到数组的末尾,同时保持非零元素的相对顺序。数组

示例:函数

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

说明:code

必须在原数组上操做,不能拷贝额外的数组。
尽可能减小操做次数。

思路

删除元素0使用splice(),添加数组元素使用push().
注意下标的计算。ip

JavaScript实现

/**
 * @param {number[]} nums
 * @return {void} Do not return anything, modify nums in-place instead.
 */
var moveZeroes = function(nums) {
    let n = nums.length;
    for(let i = 0; i < n;){
        if(nums[i] == 0){
            nums.splice(i,1);
            nums.push(0);
            n--;
        }else{
            i++;
        }
    }
};
相关文章
相关标签/搜索