【題目】
給你一個未排序的整數數組,請你找出其中沒有出現的最小的正整數。
【題目解析】
飛機對號入座,原地O(N)解法!
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
for a in nums: #遍歷每個座位,記當前坐着a號乘客
while 0<a<=len(nums) and a!=nums[a-1]: #乘客a是正票但坐錯了! 其座位被 ta=nums[a-1]佔了
nums[a-1], a = a, nums[a - 1] # a和ta兩人互換則a對號入座。此後ta相當於新的a,去找自己的座位(循環執行)
#print(nums)
for i in range(len(nums)):
if i+1!=nums[i]:
return i+1 #找到首個沒有對號入座的nums[i]!=i+1
return len(nums)+1 #滿座,返回N+1
注意:
題解中:如果將:nums[a-1], a = a, nums[a-1] 換成 a, nums[a-1] = nums[a-1], a 是錯誤的!