Classical algorithm (10) An interesting Google face test

Source: Internet
Author: User
Tags hash sort

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.