0%

two-sum-iii-data-structure-design

Two Sum III - Data structure design – LeetCode 170

Problem

Description

Design and implement a TwoSum class. It should support the following operations:add and find.

add - Add the number to an internal data structure.

find - Find if there exists any pair of numbers which sum is equal to the value.

Example

add(1); add(3); add(5);
find(4) -> true
find(7) -> false

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class TwoSum {
public:
void add(int number) {
++m[number];
}
bool find(int value) {
for (auto a : m) {
int t = value - a.first;
if ((t != a.first && m.count(t)) || (t == a.first && a.second > 1)) {
return true;
}
}
return false;
}
private:
unordered_map<int, int> m;
};

思路

重点在于原本容纳就需要n个空间,于是索性使用unordered_map,空间复杂度$O(n)$,add操作时间复杂度$O(1)$,find操作时间复杂度$O(n)$。

Better

思路

还没看到更好的解法