leetcode 41. First Missing Posit
2019-04-01 本文已影响0人
咿呀咿呀呦__
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:
def firstMissingPositive(self, nums: List[int]) -> int:
i = 1
while i in nums:
i += 1
return i
这题主要是要理解题目在说什么,其实是找最小正整数(默认情况是1),那我们只要从1开始递增,如果一直在nums中出现,那最后只要比最后在nums中出现的正整数大1就可以了
还有就是while i in nums
等效于
while True:
if i in nums:
dosomething
else:
break
一般不会这么写,但在这里这样写还算比较容易理解