-
Notifications
You must be signed in to change notification settings - Fork 0
/
170. Two Sum III - Data structure design
77 lines (58 loc) · 2.22 KB
/
170. Two Sum III - Data structure design
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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.
Example 1:
Input
["TwoSum", "add", "add", "add", "find", "find"]
[[], [1], [3], [5], [4], [7]]
Output
[null, null, null, null, true, false]
Explanation
TwoSum twoSum = new TwoSum();
twoSum.add(1); // [] --> [1]
twoSum.add(3); // [1] --> [1,3]
twoSum.add(5); // [1,3] --> [1,3,5]
twoSum.find(4); // 1 + 3 = 4, return true
twoSum.find(7); // No two integers sum up to 7, return false
Constraints:
-105 <= number <= 105
-231 <= value <= 231 - 1
At most 104 calls will be made to add and find.
设计一个数据结构,接收一个整数流,并检查它是否有一对整数的总和等于特定值。
实现 TwoSum 类:
TwoSum() 初始化 TwoSum 对象,最初为空数组。
void add(int number) 将数字添加到数据结构中。
boolean find(int value) 如果存在任意两个数字的和等于 value,则返回 true,否则返回 false。
约束条件:
-105 <= number <= 105
-231 <= value <= 231 - 1
add 和 find 最多调用 104 次。
import java.util.HashMap;
import java.util.Map;
class TwoSum {
Map<Integer, Integer> map;
public TwoSum() {
// 初始化一个空的 HashMap
map = new HashMap<>();
}
public void add(int number) {
// 将 number 的数量存入 map 中
map.put(number, map.getOrDefault(number, 0) + 1);
}
public boolean find(int value) {
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
int num = entry.getKey();
int target = value - num;
if (map.containsKey(target)) {
// 如果不是同一个数,或者同一个数的数量大于 1,则返回 true
if (num != target || map.get(num) > 1) {
return true;
}
}
}
// 没有找到对应的数对,返回 false
return false;
}
}