Recently on Weibo to see an interesting Google interview question, see the following figure:
Text version:
An array of size n, in which the number is within the range [0, n-1], with an indeterminate repeating element, finding at least one repeating element, requiring O (1) space and O (n) time.
This topic requires the time complexity of O (n), which means that only the array can be traversed once. Also looking for duplicate elements, it is easy to think of a hash table to complete, the traversal of the array of each element to map to the Hashtable, if the hash table already exists this element is a repeating element. Therefore, direct use of C + + STL Hash_set (see "STL series six sets and Hash_set") can be conveniently in O (n) time to complete the search for duplicate elements.
But the problem is limited in space complexity--the requirement is O (1) space. Therefore, the use of a hash table solution is certainly in the space complexity is not in line with the requirements. But you can continue to think along the way of hashing, in which the numbers in the array are in the range [0, n-1], so the hash table size is n. So what we actually do is hash the N ranges of 0 to n-1, and the hash table is just n. More familiar with the sorting algorithm is not difficult to find this is a classic sort algorithm--cardinal order very similar. And the time space complexity of the cardinal order just meets the question request! So try to use cardinality sorting to solve this problem.
Here's an example of the 10 numbers 2,4,1,5,7,6,1,9,0,2, showing how to sort by cardinality to find repeating elements.