美文网首页
LeetCode 移动零

LeetCode 移动零

作者: Leon_hy | 来源:发表于2019-06-19 19:55 被阅读0次

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

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

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

class Solution {
    public void moveZeroes(int[] nums) {
       if(nums == null || nums.length == 0){
            return;
        }
        //记录非o元素开始位置
        int k = 0;
        for(int i=0;i<nums.length;i++){
            if(nums[i] != 0) {
                nums[k++] = nums[i];
            }
        }
        while(k < nums.length) {
            nums[k] = 0;
            k++;
        }
    }
}


相关文章

  • 算法:数组(二)

    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-移动零

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

网友评论

      本文标题:LeetCode 移动零

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