Loading

Leetcode - 41. 缺失的第一个正数

给你一个未排序的整数数组nums,请你找出其中没有出现的最小的正整数。
请你实现时间复杂度为O(n)并且只使用常数级别额外空间的解决方案。

示例 1:

输入:nums = [1,2,0]
输出:3

示例 2:

输入:nums = [3,4,-1,1]
输出:2

示例 3:

输入:nums = [7,8,9,11,12]
输出:1

提示:

  • 1 <= nums.length <= 5 * 105
  • -231 <= nums[i] <= 231 - 1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-missing-positive
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解1 2021/9/6 O(logn)

def firstMissingPositive(nums: list) -> int:
    # 题目限定了 nums.len>=1
    ### 错误 - 2
    nums=list(set(nums))
    ### 错误 - 2
    nums.sort()
    cur=1
    for x in nums:
        if x<=0: continue
        if x!=cur: return cur
        else: cur+=1
    ### 错误 - 1
    #return nums[-1]+1
    last=nums[-1]
    return nums[-1]+1 if last>0 else 1
    ### 错误 - 1

if __name__ == '__main__':
    print(firstMissingPositive([1,2,0]))
    print(firstMissingPositive([3,4,-1,1]))
    print(firstMissingPositive([7,8,9,11,12]))
    print(firstMissingPositive([0,1,-1,7,8,9,11,12]))
    print(firstMissingPositive([0]))
    print(firstMissingPositive([5]))
    ### 错误
    # 1
    print(firstMissingPositive([-5]))
    print(firstMissingPositive([-5,-3]))
    print(firstMissingPositive([-5,-3,0]))
    # 2, 没考虑重复的情况
    print(firstMissingPositive([0, 2, 2, 1, 1]))

posted @ 2021-09-06 08:50  wwcg2235  阅读(28)  评论(0)    收藏  举报