题目
给你一个未排序的整数数组,请你找出其中没有出现的最小的正整数。
示例 1:
输入: [1,2,0]
输出: 3
示例 2:
输入: [3,4,-1,1]
输出: 2
示例 3:
输入: [7,8,9,11,12]
输出: 1
解题思路
Use number value as the index, find a way to label those appeared numbers.
Because we want to find the first positive number, and if all of the positive appeared, then the nums
would be in the range: [1, n]
.
We can delete those numbers out of this range first, by making them 0s. Then go through the list, if the number is in this range, then the new index would be: val - 1
. Use this index to change the number. We use add n + 1
here, we can’t use * -1
here because we change the numbers to 0
when we deleting them. If the index is called, and the value is 0, we can’t tell if the index is called or not by the final result.
Time complexity:
o
(
n
)
o(n)
o(n)
Space complexity:
o
(
1
)
o(1)
o(1)
代码
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
n = len(nums)
# delete other numbers
for i in range(len(nums)):
if nums[i] <= 0 or nums[i] > n:
nums[i] = 0
# transform all the numbers
for each_num in nums:
each_num %= (n + 1)
if 1 <= each_num <= n:
index = each_num - 1
nums[index] += n + 1
# check the final results
for i in range(len(nums)):
if nums[i] < n + 1:
return i + 1
return n + 1