问题描述:

 

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重新排序

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-24
  • 2022-02-24
  • 2021-11-06
  • 2021-12-22
  • 2021-08-25
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-10
  • 2021-06-04
相关资源
相似解决方案