1. 程式人生 > >leetcode 283. Move Zeros(移動零) python3 多種思路(移動零 / 移動非零)

leetcode 283. Move Zeros(移動零) python3 多種思路(移動零 / 移動非零)


'''

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.

'''



class Solution:
    def moveZeroes(self, nums):
        """
        :type nums: List[int]
        :rtype: void Do not return anything, modify nums in-place instead.
        """
        # Approach #1: 0 個數多的時候效率低下,注意remove()與del 操作的區別,如果用del操作,列表需要倒序遍歷。
        #
#         for i in nums:
#             if i == 0:
#                 nums.remove(i)    
#                 nums.append(0)
        
        # Approach #2: 刪除後一次性補零,減少元素位移
        #
        idxs = [idx for idx , num in enumerate(nums) if num == 0]
        for i in idxs[::-1]:
            nums.pop(i)
        nums += len(idxs) *[0]    




        # Approach #3: 減少交換次數(操作次數就是非零元素的個數)
        # Time:  O(n)
        # Space: O(1)
        #
        j = 0   # 記錄非零元素應該換到第幾個位置
        for i in range(len(nums)):
            if nums[i] != 0:       
                nums[j], nums[i] = nums[i], nums[j]
                j += 1