美文网首页
力扣283 - 移动零

力扣283 - 移动零

作者: gaookey | 来源:发表于2020-09-02 17:32 被阅读0次

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

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

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

func moveZeroes(_ nums: inout [Int]) {
    
    var j = 0
    for i in 0..<nums.count {
        if nums[i] != 0 {
            nums[j] = nums[i]
            if i != j {
                nums[i] = 0
            }
            j += 1
        }
    }
}

var nums = [0,1,0,3,12]
//[1, 3, 12, 0, 0]
moveZeroes(&nums)

相关文章

  • 新手算法题目

    数组 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/idjpsktx.html