qianlei90 / Blog

那些该死的文字呦
https://qianlei.notion.site
103 stars 20 forks source link

283. Move Zeroes #24

Open qianlei90 opened 7 years ago

qianlei90 commented 7 years ago

283. Move Zeroes

Tags: 印象笔记

[toc]


Question

Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = `[0, 1, 0, 3, 12]`, after calling your function, nums should be `[1, 3, 12, 0, 0]`.

note

1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.

Solution 1

列表操作题,利用python的list特性,很简单。直接把0删除,然后在末尾添加被删除的0就好。

Show me the code

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        original_len = len(nums)
        while 0 in nums:
            nums.remove(0)
        nums.extend([0] * (original_len - len(nums)))

Solution 2

利用list的sort方法,对元素进行排序。sort方法中有个参数是key,key用来为每个元素提取比较值.,默认为 None,,即直接比较每个元素。

Show me the code 1

可以构造一个lambda函数,如果元素的值为0,则返回TrueTrueFalse大,元素就排到了后面。

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        nums.sort(key=lambda x: x is 0)

Show me the code 2

将lambda函数简化,简化为1个操作符即可。

class Solution(object):
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        nums.sort(key=operator.not_)

- 完 -