Description
Given an unsorted integer array, find the smallest missing positive integer.
Note:
Your algorithm should run in O(n) time and uses constant extra space.
Example
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
Submissions
首先理解题意是找出列表中缺失的最小正整数。刚开始我理解错了题意以为输出列表中间缺失的最小正整数,之后结果例子是从1开始遍历的最小正整数.于是利用Python,首先判断列表是否为空,如果为空则直接输出1,如果不为空,则从1到列表中正整数最大值的后一位从小到大依次进行遍历,判断是否在列表num中,如果不在则直接返回即可.
实现代码如下:
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
if nums == []:
return 1
for i in range(1, max(max(nums),1) + 2):
if i not in nums:
return i