LeetCode-283-移动零

  |   0 评论   |   0 浏览

题目描述:

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

示例:

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

必须在原数组上操作,不能拷贝额外的数组。
尽量减少操作次数。

解法:

先遍历数据,把不为空的数字移动到数组前面,记录下不为空的个数j,大于j小于nums.length 的位置都填充为零

public void moveZeroes(int[] nums) {
        int j = 0; int length = nums.length;
        for(int i = 0; i < length; i++) {
            if (nums[i] != 0) {
                nums[j++] = nums[i];
            }
        }
        while(j < length) {
            nums[j++] = 0;
        }
}

运行结果:

image.png


标题:LeetCode-283-移动零
作者:guobing
地址:http://www.guobingwei.tech/articles/2020/11/08/1604823602465.html