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

后端 未结 15 2276
暖寄归人
暖寄归人 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 08:03

    Here's a Python 3 implementation of pmcarpan's answer.

    def missing_int(nums: MutableSequence[int]) -> int:
        # If empty array or doesn't have 1, return 1
        if not next((x for x in nums if x == 1), 0):
            return 1
    
        lo: int = 0
        hi: int = len(nums) - 1
        i: int = 0
        pivot: int = 1
    
        while i <= hi:
            if nums[i] < pivot:
                swap(nums, i, hi)
                hi -= 1
            elif nums[i] > pivot:
                swap(nums, i, lo)
                i += 1
                lo += 1
            else:
                i += 1
    
        x = 0
        while x <= hi:  # hi is the index of the last positive number
            y: int = abs(nums[x])
            if 0 < y <= hi + 1 and nums[y - 1] > 0:  # Don't flip sign if already negative
                nums[y - 1] *= -1
            x += 1
    
        return next((i for i, v in enumerate(nums[:hi + 1]) if v >= 0), x) + 1
    

    Tests:

    def test_missing_int(self):
        assert func.missing_int([1, 2, 1, 0]) == 3
        assert func.missing_int([3, 4, -1, 1]) == 2
        assert func.missing_int([7, 8, 9, 11, 12]) == 1
        assert func.missing_int([1]) == 2
        assert func.missing_int([]) == 1
        assert func.missing_int([0]) == 1
        assert func.missing_int([2, 1]) == 3
        assert func.missing_int([-1, -2, -3]) == 1
        assert func.missing_int([1, 1]) == 2
        assert func.missing_int([1000, -1]) == 1
        assert func.missing_int([-10, -3, -100, -1000, -239, 1]) == 2
        assert func.missing_int([1, 1]) == 2
    

提交回复
热议问题