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

前端 未结 4 632
余生分开走
余生分开走 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:20

    In fact, since the number of elements in the array was fix, you could do much better than what you have proposed.

    By "creating a map with index as the number in the array and the value as the frequency of the number occurring in the array", you create a map with 2^32 positions (assuming the array had 32-bit integers), and then you have to pass though that map to find the first position whose value is one. It means that you are using a large auxiliary space and in the worst case you are doing about 10^6+2^32 operations (one million to create the map and 2^32 to find the element).

    Instead of doing so, you could sort the array with some n*log(n) algorithm and then search for the element in the sorted array, because in your case, n = 10^6.

    For instance, using the merge sort, you would use a much smaller auxiliary space (just an array of 10^6 integers) and would do about (10^6)*log(10^6)+10^6 operations to sort and then find the element, which is approximately 21*10^6 (many many times smaller than 10^6+2^32).

    PS: sorting the array decreases the search from a quadratic to a linear cost, because with a sorted array we just have to access the adjacent positions to check if a current position is unique or not.

提交回复
热议问题