LeetCode283:Move Zeroes
阿新 • • 發佈:2018-11-12
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:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
LeetCode:連結
一共有三種方法。
第一種:建立一個新列表,把不為0的數字加進去,然後再把0加進去。時間複雜度O(n),空間複雜度O(n)。
第二種:將滿足的放到前面,不滿足的直接覆蓋,首先找到第一個0記錄位置i,再找到第一個非0記錄位置j,將j的值賦值給i的位置,覆蓋後i向後移動一個位置,j繼續向後查詢非0元素,重複賦值的過程直至j走到陣列的最後。然後將i後面的數字賦值為0。時間複雜度O(n),空間複雜度O(1)。
第三種:將滿足的放到前面,不滿足的直接交換到後面。本題就是採用了交換的方式,首先找到第一個0記錄位置i,再找到第一個非0記錄位置j,將i與j交換,交換後i向後移動一個位置,j繼續向後查詢非0元素,重複交換的過程直至j走到陣列的最後 。
class Solution(object): def moveZeroes(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ start = 0 for i in range(len(nums)): if nums[i] != 0: nums[start], nums[i] = nums[i], nums[start] start += 1