Find the only unique element in an array of a million elements

前端 未结 4 633
余生分开走
余生分开走 2021-01-04 09:46

I was asked this question in a recent interview.

You are given an array that has a million elements. All the elements are duplicates except one. My task is to find t

4条回答
  •  感动是毒
    2021-01-04 10:30

    I'm certain that you can't solve this problem without going through the whole array, at least if you don't have any additional information (like the elements being sorted and restricted to certain values), so the problem has a minimum time complexity of O(n). You can, however, reduce the memory complexity to O(1) with a XOR-based solution, if every element is in the array an even number of times, which seems to be the most common variant of the problem, if that's of any interest to you:

    int unique(int[] array)
    {
        int unpaired = array[0];
        for(int i = 1; i < array.length; i++)
            unpaired = unpaired ^ array[i];
        return unpaired;
    }
    

    Basically, every XORed element cancels out with the other one, so your result is the only element that didn't cancel out.

提交回复
热议问题