標籤:額外 object solution question oca 記錄 reverse odi self
https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/1/array/28/
給定一個數組 nums
,編寫一個函數將所有 0
移動到數組的末尾,同時保持非零元素的相對順序。
樣本:
輸入: [0,1,0,3,12]
輸出: [1,3,12,0,0]
說明:
- 必須在原數組上操作,不能拷貝額外的數組。
- 盡量減少操作次數。
此題有兩個思路:
1. 採用類似於冒泡排序的思想,從後往前遍曆,如果遇到0就把0和後面的數字交換位置,直到最後一個可用位置(需要記錄)。時間複雜度是O(N^2),空間複雜度是O(1)
1 class Solution(object): 2 def moveZeroes(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: void Do not return anything, modify nums in-place instead. 6 """ 7 index_range = range(len(nums)) 8 reverse_index_range = index_range[::-1] 9 available_location = len(nums) - 110 for i in reverse_index_range:11 if nums[i] != 0:12 continue13 else:14 j = i + 115 while True:16 if j > available_location:17 break18 temp = nums[j-1]19 nums[j-1] = nums[j]20 nums[j] = temp21 j = j + 122 available_location -= 1
2. 遍曆第一次,將所有的非零值都移動到最前面,壓縮的思想;遍曆第二次,將前面壓縮後的剩餘空間都置0。時間複雜度是O(N),空間複雜度是O(1)
1 class Solution(object): 2 def moveZeroes(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: void Do not return anything, modify nums in-place instead. 6 """ 7 available_location = 0 8 for i in range(len(nums)): 9 if nums[i] == 0:10 continue11 else:12 nums[available_location] = nums[i]13 available_location += 114 for i in range(available_location,len(nums)):15 nums[i] = 0
LeetCode 移動零