美文网首页
LeetCode 数组 移动零

LeetCode 数组 移动零

作者: Eddiehe212 | 来源:发表于2018-08-12 12:35 被阅读0次

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

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

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

解答:
此处我们需要了解python的三种删除方式,del list[index] 删除对应index的元素,index自动重排序;list.remove(obj) 删除对应值为obj的元素,不改index;list.pop(index)删除制定index的元素。

class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        org = len(nums)
        index=0
        for i in range(org):
        '''i 只是用于记录操作次数,和index毫无关系。
        remove是删除list中第一次出现的某个元素,
        del 是删除对应index的元素'''
        
            if nums[index]==0:
                nums.append(0)
                del nums[index]
            else:
                index+=1

相关文章

  • LeetCode 数组 移动零

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

  • LeetCode热门100题算法和思路(day8)

    LeetCode283 移动零 题目详情 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保...

  • 算法时间 I

    1. 移动零[https://leetcode.cn/problems/move-zeroes/] 给定一个数组 ...

  • 2019-02-21 Day 47

    1.移动零来源 LeetCode给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素...

  • leetcode之移动零

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

  • 算法:数组(二)

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

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

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

  • leecode刷题(8)-- 移动零

    leecode刷题(8)-- 移动零 移动零 描述: 给定一个数组 nums,编写一个函数将所有 0 移动到数组的...

  • LeetCode 移动零

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

  • LeetCode—— 移动零

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

网友评论

      本文标题:LeetCode 数组 移动零

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