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

后端 未结 15 2279
暖寄归人
暖寄归人 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条回答
  •  旧时难觅i
    2021-02-01 07:47

    Drawback of the above approach is it takes extra space for assigning "max_value" which is not the right solution

    def missing_positive_integer(my_list):
        max_value = max(my_list)
        my_list = [num for num in range(1,max(my_list)) if num not in my_list]
        if len(my_list) == 0:
            my_list.append(max_value+1)
    
        return min(my_list)
    
    my_list = [1,2,3,4,5,8,-1,-12,-3,-4,-8]
    missing_positive_integer(my_list)
    

提交回复
热议问题