Algorithm to determine if array contains n…n+m?

前端 未结 30 3106
清酒与你
清酒与你 2020-11-28 01:45

I saw this question on Reddit, and there were no positive solutions presented, and I thought it would be a perfect question to ask here. This was in a thread about interview

30条回答
  •  感情败类
    2020-11-28 01:57

    I like Greg Hewgill's idea of Radix sorting. To find duplicates, you can sort in O(N) time given the constraints on the values in this array.

    For an in-place O(1) space O(N) time that restores the original ordering of the list, you don't have to do an actual swap on that number; you can just mark it with a flag:

    //Java: assumes all numbers in arr > 1
    boolean checkArrayConsecutiveRange(int[] arr) {
    
    // find min/max
    int min = arr[0]; int max = arr[0]
    for (int i=1; i max ? arr[i] : max);
    }
    if (max-min != arr.length) return false;
    
    // flag and check
    boolean ret = true;
    for (int i=0; i

    Storing the flags inside the given array is kind of cheating, and doesn't play well with parallelization. I'm still trying to think of a way to do it without touching the array in O(N) time and O(log N) space. Checking against the sum and against the sum of least squares (arr[i] - arr.length/2.0)^2 feels like it might work. The one defining characteristic we know about a 0...m array with no duplicates is that it's uniformly distributed; we should just check that.

    Now if only I could prove it.

    I'd like to note that the solution above involving factorial takes O(N) space to store the factorial itself. N! > 2^N, which takes N bytes to store.

提交回复
热议问题