Determine whether or not there exist two elements in Set S whose sum is exactly x - correct solution?

后端 未结 8 2109
醉梦人生
醉梦人生 2020-12-04 19:48

Taken from Introduction to Algorithms

Describe a Θ(n lg n)-time algorithm that, given a set S of n integers and another integer x, determines whet

8条回答
  •  生来不讨喜
    2020-12-04 20:03

    There's another very fast solution: Imagine you have to solve this problem in Java for about 1 billions integers. You know that in Java integers go from -2**31+1 to +2**31.

    Create an array with 2**32 billion bit (500 MB, trivial to do on today's hardware).

    Iterate over your set: if you have an integer, set corresponding bit to 1.

    O(n) so far.

    Iterate again over your set: for each value, check if you have a bit set at "current val - x".

    If you have one, you return true.

    Granted, it needs 500 MB of memory.

    But this shall run around any other O(n log n) solution if you have, say, to solve that problem with 1 billion integers.

    O(n).

提交回复
热议问题