美文网首页
283. 移动零

283. 移动零

作者: 邦_ | 来源:发表于2022-07-21 09:40 被阅读0次

本来想着边删除边移动。。发现删除操作也是消耗性能的= =。。似乎交换的写法比较好


func moveZeroes(_ nums: inout [Int]) {
        let len = nums.count
        if len == 1 {
            return
        }
        var count = 0
        nums.removeAll { num in
            if num == 0 {
                count += 1
                return true
            }
            return false
        }
        
        if count > 0 {
            for _  in 0..<count {
                nums.append(0)
            }
        }
    }

用cur 记录为0的位置 遇到不是0的 把值赋值给cur的位置 不是0的位置赋值为0 cur赋值不是0的索引
思路比较难懂= =。。



 func moveZeroes(_ nums: inout [Int]) {
        let len = nums.count
        if len == 1 {
            return
        }
        //cur 用来标记0的位置
        var cur = 0
        for i in 0..<len {
            if nums[i] == 0 {
                continue
            }
            if cur != i{
                nums[cur] = nums[i]
                nums[i] = 0
            }
            cur += 1

            
        }
        
    }






相关文章

  • 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/aeeeirtx.html