美文网首页程序员
力扣 283 移动零

力扣 283 移动零

作者: zhaojinhui | 来源:发表于2020-08-17 11:08 被阅读0次

题意:给定一个数组,把其中的0都移动到最后

思路:设一个end指针记录第一个为0的index

  1. 遍历数组,把非0的数字按遍历到的顺序添加到end指针,并增加end
  2. 遍历数组,从end开始到数组末尾设为0

思想:快慢指针

复杂度:时间O(n),空间O(1)

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

相关文章

  • 新手算法题目

    数组 Array力扣 485最大连续1的个数 | Max Consecutive One力扣 283 移动零 |...

  • 算法:数组(二)

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

  • 力扣 283 移动零

    题意:给定一个数组,把其中的0都移动到最后 思路:设一个end指针记录第一个为0的index 遍历数组,把非0的数...

  • 力扣283 - 移动零

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

  • 力扣-283-移动零-双指针

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

  • 283. 移动零

    283. 移动零

  • 力扣 273 移动零

    题意:给定一个数,把他用英文表示 思路:具体可见代码注释 思想:字符串的处理 复杂度:时间O(n),空间O(n)

  • LeetCode 数组专题 2:一些关于数组的问题

    例题1:LeetCode 第 283 题:移动零 传送门:英文网址:283. Move Zeroes ,中文网址:...

  • LeetCode考试

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

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

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

网友评论

    本文标题:力扣 283 移动零

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