-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTwoSum3.java
More file actions
51 lines (44 loc) · 1.44 KB
/
Copy pathTwoSum3.java
File metadata and controls
51 lines (44 loc) · 1.44 KB
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
package leetcode;
import java.util.*;
/*
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.
For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
*/
class TwoSum3{
private List<Integer> list = new ArrayList<Integer>();
private Map<Integer, Integer> map = new HashMap<Integer, Integer>();
// Add the number to an internal data structure.
public void add(int number) {
if (map.containsKey(number)) map.put(number, map.get(number) + 1);
else {
map.put(number, 1);
list.add(number);
}
}
// Find if there exists any pair of numbers which sum is equal to the value.
public boolean find(int value) {
for (int i = 0; i < list.size(); i++){
int num1 = list.get(i), num2 = value - num1;
if ((num1 == num2 && map.get(num1) > 1) || (num1 != num2 && map.containsKey(num2))) return true;
}
return false;
}
public static void main(String[] args) {
TwoSum3 ts3 = new TwoSum3();
ts3.add(1);
ts3.add(3);
ts3.add(5);
System.out.println(ts3.find(1));
System.out.println(ts3.find(4));
System.out.println(ts3.find(7));
System.out.println(ts3.find(8));
ts3.add(2);
System.out.println(ts3.find(7));
}
}