Python3解leetcode Binary Tree PathsAdd DigitsMove Zeroes

问题描述:

 

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.

 

Example:

 

Input: [0,1,0,3,12]
Output: [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.

 

思路:

主要是list的sort()函数的应用

代码:

 

 def moveZeroes(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        nums.sort(key = lambda x: x ==0)

 

key是sort()函数中的一个参数,该参数指定排序的元素。当前代码中排序元素就是nums中所有0元素,到最后所有0元素一组(新),除去0元素的其他元素一组(老),最终默认按照老-新的顺序将nums重新排序

 

posted on 2019-07-17 14:13  狂奔的蜗牛163  阅读(138)  评论(0编辑  收藏  举报