【发布时间】:2022-11-07 12:10:06
【问题描述】:
问题https://leetcode.com/problems/first-missing-positive/ 提出:
给定一个未排序的整数数组 nums,返回最小的缺失正整数。
您必须实现一个在 O(n) 时间内运行并使用恒定额外空间的算法。
示例 1:
Input: nums = [1,2,0]
Output: 3
Example 2:
Input: nums = [3,4,-1,1]
Output: 2
Example 3:
Input: nums = [7,8,9,11,12]
Output: 1
Constraints:
1 <= nums.length <= 5 * 10**5
-2**31 <= nums[i] <= 2**31 - 1
因此我的代码满足了这一点:
class Solution:
def firstMissingPositive(self, nums: List[int]) -> int:
nums=sorted(list(filter(lambda x: x>=0, nums)))
nums= list(dict.fromkeys(nums))
if 1 not in nums: return 1
x=nums[0]
for num in nums:
if nums.index(num) != 0:
dif = num - x
if dif!=1:
return x + 1
x=num
return num+1
很高兴有人提供帮助。
【问题讨论】:
-
那不是 O(n)。你排序了!
-
你一遍又一遍地打电话给
index! -
而且您也没有像他们告诉您的那样使用恒定的额外空间!
-
@user2357112supportsMonica 谢谢,我认为排序是 o(n)
-
list.index是 O(n)。您将其称为最坏情况 n 次。所以这个算法变成了O(n**2)
标签: python