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

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

    My solution in Python:

    def lowest_positive(lista):
    
    result = 0
    dict = {}
    
    for i in lista:
    
        if i <= 0:
            continue
    
        if i in dict:
            continue
        else:
            dict[i] = i
    
            if result == 0:
                result = result +1
    
            if result < i: 
                continue
    
            result = result +1
    
            while result in dict:
                result = result +1
    
    return result
    

    Test cases:

    lista = [5, 3, 4, -1, 1, 2]
    lista = [1,2,3,4,5]
    lista = [3, 4, -1, 1]
    lista = [2, 3, 4, 1]
    lista = [1,0]
    lowest_positive(lista)
    

    Please note, I am not considering 0 as positive number

    Logic: If number is less than 0, it is rejected. Then the number is checked in dictionary if it exist, if yes, the next number is read else it is added to the dictionary. result is the counter which is incremented one by one. if result is less than the number read in the list, the next number is read else, the counter is increased by one and this result is also checked in dictionary. Dictionary in all will store all the number read in the list, plus any missing positive numbers in between the smallest number read in the list.

提交回复
热议问题