Given an array of integers, find the first missing positive integer in linear time and constant space

后端 未结 15 2397
暖寄归人
暖寄归人 2021-02-01 07:17

In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. This question was asked by Stri

15条回答
  •  情深已故
    2021-02-01 07:58

    I solved the problem using set in python3. It is very simple 6LOC. time complexity: O(n).

    Remember: Membership check in set is O(1)

    def first_missing_positive_integer(arr):
        arr = set(arr)
        for i in range(1, len(arr)+2):
            if i not in arr:
                return i
    

提交回复
热议问题