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

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

提交回复
热议问题