Finding missing elements in an array

前端 未结 9 1301
我寻月下人不归
我寻月下人不归 2020-12-23 10:43

Given you have an array A[1..n] of size n, it contains elements from the set {1..n}. However, two of the elements are missing, (and perhaps two of the array elements are rep

9条回答
  •  再見小時候
    2020-12-23 11:29

    Cycle each element 0...n-1.

    x = abs(A[i]) (with i = 0...n-1);
    
    A[x - 1] can be: 
    > 0: we haven't checked the element, change its sign to negative:
        A[x - 1] = -A[x - 1]
    < 0: we already found the same number
    

    At the end of the cycle, pass each A[0...n-1]. The index of the positive elements + 1 is the missing numbers.

    So if

    y = abs(A[i]) > 0: i + 1 is missing.
    

    In C#

    var arr = new[] { 1, 2, 1, 2, 4 };
    
    for (int i = 0; i < arr.Length; i++) {
        int x = Math.Abs(arr[i]);
        int y = arr[x - 1];
        if (y > 0) {
            arr[x - 1] = -arr[x - 1];
        }
    }
    
    for (int i = 0; i < arr.Length; i++) {
        int x = arr[i];
        if (x > 0) {
            Console.WriteLine("Missing {0}", i + 1);
        } else {
            arr[i] = -arr[i];
        }
    }
    

    And the array is as good as new.

提交回复
热议问题