method 1:可以通过,但不满足空间O(1)
当s 不是集合无法通过。数字 i 一定在1到数组长度加1之间,比如nums = [1, 2, 3], 那么结果为4
nums = [1, 2, 2], 结果为 3
Runtime: 1346 ms, faster than 9.34% of Python3 online submissions for First Missing Positive.
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
s = set(nums)
for i in range(1, len(nums) + 2):
if i not in s:
return i
method 2: 利用下标标记已经访问数字
1 检查是否有负数及0,如果有, 变为len(nums) + 1
2 把访问过的数字存在下标的位置上,用负数作标记
3 读取第一个正数或者利用长度+ 1
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
# keep all positive
for idx in range(len(nums)):
if nums[idx] <= 0 or nums[idx] > len(nums):
nums[idx] = len(nums) + 1
# placing marker
for num in nums:
num = abs(num) # avoid wrong doing of negative marking
if num <= len(nums) and nums[num - 1] >= 0: # num <= len(nums), avoid index out of range
nums[num - 1] *= -1
# get res
for idx in range(len(nums)):
if nums[idx] > 0:
return idx + 1
return len(nums) + 1