day10笔记
1.题目描述
2.代码构思(debug)
方法1: 哈希表,不满足空间复杂度要求, 长度为n的数组, 不存在的正数一定在【0,n+1】闭区间之内
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
if not nums:
return nums
d = {}
for item in nums:
if item not in d:
d[item] = 1
else:
d[item] += 1
left = 1
while left <= len(nums):
if left not in d:
return left
else:
left += 1
return left
## 方法2:
将数组本身下标当作idx处理
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
if not nums:
return nums
if 1 not in nums:
return 1
len1 = len(nums)
for i in range(len1):
if nums[i] <= 1:
nums[i] = 1
for i in range(len1):
num = abs(nums[i])
if num <= len1:
nums[num - 1] = -abs(nums[num - 1])
for i in range(1,len1):
if nums[i] > 0 and nums[i - 1] < 0:
return i + 1
return len1 + 1