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

后端 未结 15 2227
暖寄归人
暖寄归人 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:54

    Here's another python implementation with o(n) time complexity and o(1) space complexity

    def segregate(arr):
        length = len(arr)
        neg_index = length
        for i, value in enumerate(arr):
            if(value < 1 and neg_index == length):
               neg_index = i
            if(neg_index != length and value >= 1):
               temp = arr[i]
               arr[i] = arr[neg_index]
               arr[neg_index] = temp
               neg_index += 1
        return arr[:neg_index]
    
    def missingPositiveNumber(arr):
        arr = segregate(arr)
        length = len(arr)
        for i, value in enumerate(arr):
            if(value - 1 < l):
               arr[abs(value) - 1] = -(abs(arr[abs(value) - 1]))
        for i, value in enumerate(arr):
            if(value > 0):
               return i + 1
        return length + 1
    
    
    print(missingPositiveNumber([1, -1, 2, 3]))
    

提交回复
热议问题