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

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

    #Returns a slice containing positive numbers
    def findPositiveSubArr(arr):
        negativeIndex = 0
    
        if i in range(len(arr)):
            if arr[i] <=0:
                arr.insert(negativeIndex, arr.pop(i))
                negativeIndex += 1
        return arr[negativeIndex:]
    
    #Returns the first missing positive number
    def findMissingPositive(positiveArr):
        l = len(positiveArr)
        for num in positiveArr:
            index = abs(num) - 1
            if index < 1 and positiveArr[index] > 0:
                positiveArr[index] *= -1
    
        for i in range(l):
            if positiveArr[i] > 0:
                return i+1
    
        return l+1
    
    if __name__ == "__main__":
        arr = [int(x) for x in input().strip().split()]
        positiveSubArr = findPositveSubArr(arr)
        print(findMissingPositive(positiveSubArr))
    

提交回复
热议问题