Leetcode
41. First Missing Positive
Given an unsorted integer array, find the smallest missing positive integer.
Example 1:
Input: [1,2,0] Output: 3
Example 2:
Input: [3,4,-1,1] Output: 2
Example 3:
Input: [7,8,9,11,12] Output: 1
Note:
Your algorithm should run in O(n) time and uses constant extra space.
代碼如圖所示
class Solution(object):
def firstMissingPositive(self, nums):
if nums:
max_num = max(nums)
i = 0
l = list(range(0, max_num + 2))
while i < len(nums):
if (nums[i] >= 1):
l[nums[i]] = -1
i += 1
i = 1
while i < max_num + 2:
if l[i] != -1:
return l[i]
i += 1
else:
return 1
題解:題目的意思是需要尋找一個列表中缺失的最小正整數。
先尋找給定列表nums中的最大數字max_num。
開一個大小爲max_num+2數組 l(當然max_num可能是負數,這裏leetcode上似乎沒有考慮到),
用下標表示是否nums中是否存在這個數字,若存在這個數n,則將l[n]的值置爲-1。
考慮到可能給定列表中缺失的最小正整數可能比列表中的最大數字大,因此開的數組大小比最大數字大1
當然需要判斷列表是否爲空,若爲空,由定義自然返回1。
遍歷一次之後,再遍歷一次,從l的下標1開始,碰到一個列表下標對應的值不爲-1的,那麼這個數就是要找的數。