1.問題描述
給你一個未排序的整數數組,請你找出其中沒有出現的最小的正整數。
示例 1:
輸入: [1,2,0]
輸出: 3
示例 2:
輸入: [3,4,-1,1]
輸出: 2
示例 3:
輸入: [7,8,9,11,12]
輸出: 1
提示:
你的算法的時間複雜度應爲O(n),並且只能使用常數級別的額外空間。
2.解題代碼
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n = len(nums)
# 如果1不在列表中,則直接返回1
if 1 not in nums:
return 1
# 將列表中小於等於0或者大於n的元素重新設置爲1
for i in range(n):
if nums[i] <= 0 or nums[i] > n:
nums[i]=1
# 遍歷列表,當讀到當前數字時,將下標爲(當前數字-1)的數字變爲負值
for i in range(n):
a = abs(nums[i])-1
nums[a] = -abs(nums[a])
# 遍歷列表,返回第一個正數元素下標+1
for i in range(n):
if nums[i] > 0:
return i+1
# 如果沒有正數元素,則返回n+1
return n+1