In less-than-linear time, find the duplicate in a sorted array

前端 未结 7 1679
名媛妹妹
名媛妹妹 2020-12-31 11:00

Today, an interviewer asked me this question. My immediate response was that we could simply do a linear search, comparing the current element with the previous element in t

7条回答
  •  余生分开走
    2020-12-31 11:03

    The example array is a little bit different from your question. Since n is the length of array and there are one and only duplicate in array, the value of each element in array should be in [0,n-1].

    If that is true, then this question is the same one with How to find a duplicate element in an array of shuffled consecutive integers?

    The following code should find the duplicate in O(n) time and O(1) space.

    public static int findOnlyDuplicateFromArray(int[] a, boolean startWithZero){
        int xor = 0;
        int offset = 1;
        for(int i=0; i < a.length; i++){
            if(startWithZero)
                xor = xor ^ (a[i] + offset) ^ i;
            else
                xor = xor ^ a[i] ^ i;
            }
            if(startWithZero)
                xor = xor - offset;
        return xor;
    }
    

提交回复
热议问题