题目:
给定一个未排序的整数数组,找出其中没有出现的最小的正整数。
示例 1:
输入: [1,2,0]
输出: 3
示例 2:
输入: [3,4,-1,1]
输出: 2
示例 3:
输入: [7,8,9,11,12]
输出: 1
说明:
你的算法的时间复杂度应为O(n),并且只能使用常数级别的空间。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-missing-positive
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
因为要求时间复杂度和空间复杂度,因此不能对数组排序再操作。
在回复中看到一个精妙的解答,直接遍历1到n,哪个数值不在数组中,这个数就是缺失的,遍历完都不缺失,直接数组长度加1.
代码:
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 1
for i in range(1,len(nums)+1):
if i not in nums:
return i
return len(nums)+1