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

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

    Javascript implementation of PMCarpan's algorithm

    function getMissingInt(array) {
      const segArray = array.filter((a) => a > 0);
      for (let i = 0; i < segArray.length; i++) {
        const value = Math.abs(segArray[i]);
        if (value <= segArray.length && segArray[value - 1] > 0) {
          segArray[value - 1] *= -1;
        }
      }
      for (let i = 0; i < segArray.length; i++) {
        if (segArray[i] > 0) {
          return i + 1;
        }
      }
      return segArray.length + 1;
    }
    console.log(getMissingInt([1, -1, -5, -3, 3, 4, 2, 8]));
    console.log(getMissingInt([3, 4, -1, 1]));
    console.log(getMissingInt([1, 2, 0]));

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2021-02-01 08:08

    It is much simpler. (Solution is not mine)

    public static int Missing(int[] a)
    {
        // the idea is to put all values in array on their ordered place if possible
        for (int i = 0; i < a.Length; i++)
        {
            CheckArrayAtPosition(a, i);
        }
    
        for (int i = 0; i < a.Length; i++)
            if (a[i] != i + 1)
                return i + 1;
        return a.Length + 1;
    }
    
    private static void CheckArrayAtPosition(int[] a, int i)
    {
        var currentValue = a[i];
        if (currentValue < 1) return; // do not touch negative values because array indexes are non-negative
        if (currentValue > a.Length) return; // do not touch values that are bigger than array length because we will not locate them anyway
        if (a[currentValue - 1] == currentValue) return; // do not need to change anything because index contain correct value already
        Swap(a, i, currentValue - 1);
        CheckArrayAtPosition(a, i); // now current position value is updated so we need to check current position again
    }
    
    private static void Swap(int[] a, int i, int j)
    {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
    

    There is a recursion but since each Swap puts 1 value to the correct place there will be <= n swaps. Linear time

    0 讨论(0)
提交回复
热议问题