Array Homework Question

前端 未结 9 1280
庸人自扰
庸人自扰 2020-12-23 16:48

You are given an array with integers between 1 and 1,000,000. One integer is in the array twice. How can you determine which one? Can you think of a way to do it using littl

9条回答
  •  鱼传尺愫
    2020-12-23 17:04

    Assuming all the numbers from 1 to 1,000,000 are in the array, the sum of all numbers from 1 to 1,000,000 is (1,000,000)*(1,000,000 + 1)/2 = 500,000 * 1,000,001 = 500,000,500,000.

    So just add up all the numbers in the array, subtract 500,000,500,000, and you'll be left with the number that occured twice.

    O(n) time, and O(1) memory.

    If the assumption isn't true, you could try using a Bloom Filter - they can be stored much more compactly than a hash table (since they only store fact of presence), but they do run the risk of false positives. This risk can be bounded though, by our choice of how much memory to spend on the bloom filter.

    We can then use the bloom filter to detect potential duplicates in O(n) time and check each candidate in O(n) time.

提交回复
热议问题