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

后端 未结 15 2236
暖寄归人
暖寄归人 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
    闹比i (楼主)
    2021-02-01 07:43

    PMCarpan's algorithm works.

    I think your approach works, but you should specify the type of sort you're doing so that it is clear it is a linear sort and not necessarily a full sort of the entire array. This results in O(N) time without using any space.

    Scan the array, as you're scanning if the value in your current index is less than the length of the array then swap it with the value currently in that index. You must continue swapping until it no longer makes sense to swap at each index. Then at the end do one more scan until you find an index that isn't correct.

    Here's some working python code, although python is not the place to do this sort of thing, lol.

    def sortOfSort(arr) :
        for index in range(len(arr)) :
            checkValue = arr[index]
    
            while(checkValue > 0 and checkValue != index and checkValue < len(arr) and arr[checkValue] != checkValue) :
                arr[index] = arr[checkValue]
                arr[checkValue] = checkValue
                checkValue = arr[index]
    
        return arr[1:] + [arr[0]]
    
    def findFirstMissingNumber(arr) :
        for x in range(len(arr)) :
            if (x+1 != arr[x]) :
                return x+1
        return len(arr) + 1
    

    the return arr[1:] part is because based on your description we aren't including zero as a starting point.

提交回复
热议问题