美文网首页
leetcode之移动零

leetcode之移动零

作者: go4it | 来源:发表于2020-11-19 23:16 被阅读0次

本文主要记录一下leetcode之移动零

题目

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

示例:

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

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


来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/move-zeroes
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

class Solution {
    public void moveZeroes(int[] nums) {
        if (nums == null || nums.length <= 1) {
            return;
        }
        int idx = 0;
        for(int i=0; i<nums.length; i++) {
            if (nums[i] != 0) {
                nums[idx] = nums[i];
                idx++;
            }
        }
        for (int i = idx; i < nums.length; i++) {
            nums[i] = 0;
        }
    }
}

小结

这里遍历数组,维护一个下标,当值不为0时则进行移动同时递增下标,遍历完一次之后,在从该下标起往后遍历,赋值为0。

doc

相关文章

  • leetcode之移动零

    序 本文主要记录一下leetcode之移动零 题目 题解 小结 这里遍历数组,维护一个下标,当值不为0时则进行移动...

  • 算法:数组(二)

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

  • 一起学算法-283. 移动零

    一、题目 LeetCode-283. 移动零链接:https://leetcode-cn.com/problems...

  • LeetCode 移动零

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

  • LeetCode—— 移动零

    题目描述 一、CPP 1. 双指针法: 解题思路:使用两个指针,指针 i 负责遍历数组,指针 j 负责其后的元素均...

  • LeetCode考试

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

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

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

  • 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/[...

网友评论

      本文标题:leetcode之移动零

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