[LeetCode] Two Sum III - Data structure design

170. Two Sum III - Data structure design

Design a data structure that accepts a stream of integers and checks if it has a pair of integers that sum up to a particular value.

Implement the TwoSum class:

  • TwoSum() Initializes the TwoSum object, with an empty array initially.
  • void add(int number) Adds number to the data structure.
  • boolean find(int value) Returns true if there exists any pair of numbers whose sum is equal to value, otherwise, it returns false.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class TwoSum {
bitset<202020> bit, sum;
int gap = 1e5;
public:
TwoSum() {}

void add(int number) {
if(number > 0) sum |= bit<<number;
else if(number == 0) sum |= bit;
else sum |= bit>>(-number);
bit[number + gap] = 1;
}

bool find(int value) {
long long x = 1ll * value + gap;
if(x < 0 or x >= 202020) return false;
return sum[x];
}
};

/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum* obj = new TwoSum();
* obj->add(number);
* bool param_2 = obj->find(value);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/02/10/PS/LeetCode/two-sum-iii-data-structure-design/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.