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.
思路:
这道题目比较直接简单。可以先将这个list按升序排列,然后设置一个target为1,接着对list内的元素进行比较:若与target相等,则target加一,表示这个target还不是最小的缺失整数;若比target大,则返回target,说明中间一定有这个target缺失。如果list内的元素都遍历完了,那就返回最后的target,因为此时缺失的整数比list内的元素都大。
代码:
class Solution:
def firstMissingPositive(self, nums):
nums.sort()
target = 1
for i in nums:
if i > target:
return target
elif i == target:
target += 1
return target