美文网首页
283. 移动零

283. 移动零

作者: 放下梧菲 | 来源:发表于2020-05-20 11:57 被阅读0次

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

示例:

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

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

本题比较简单,可以用双指针,一个指针指向0,一个指向其他数,指向0的数一直向后遍历,当遇见0就另设一指针向后移动,如果遇见了不是0的数就进行交换即可。
这是通解
而不是通解就是我们可以把所有不是0的数都向前移动。占掉原本0的位置,然后记录不是0的数。
再用一个循环把后面的数全置为0即可。
代码如下:

  • 我用的是通解
class Solution {
    public void moveZeroes(int[] nums) {
        int pointToZero = 0,pointToOther = 0;
        
        while (pointToZero < nums.length){
            if (nums[pointToZero] != 0){
                pointToZero ++;
            }
            else{
                pointToOther = pointToZero + 1;
                while (pointToOther < nums.length && nums[pointToOther] == 0) pointToOther++;
                if (pointToOther == nums.length) break;
                int temp = nums[pointToOther];
                nums[pointToOther] = 0;
                nums[pointToZero] = temp;
                pointToZero ++;
            }
        }
    }
}

相关文章

  • 283. 移动零

    283. 移动零

  • LeetCode考试

    283. 移动零](https://leetcode-cn.com/problems/move-zeroes/) ...

  • 每日一题20201119(283. 移动零)

    283. 移动零[https://leetcode-cn.com/problems/move-zeroes/] 思...

  • 算法:数组(二)

    283. 移动零 - 力扣(LeetCode) (leetcode-cn.com)[https://leetcod...

  • LeetCode 281-310

    283. 移动零[https://leetcode-cn.com/problems/move-zeroes/] 2...

  • LeetCode:283. 移动零

    问题链接 283. 移动零[https://leetcode-cn.com/problems/move-zeroe...

  • 283. 移动零

    题目地址(283. 移动零) https://leetcode.cn/problems/move-zeroes/[...

  • 283. 移动零

    题目 分析 其实题目本身并不难,主要是他要求必须在原数组上进行操作,不能拷贝额外的数组。这里用到了双指针法,快指针...

  • 283.移动零

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

  • 283. 移动零

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

网友评论

      本文标题:283. 移动零

      本文链接:https://www.haomeiwen.com/subject/flfgohtx.html