-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTwoSum.java
More file actions
47 lines (39 loc) · 901 Bytes
/
TwoSum.java
File metadata and controls
47 lines (39 loc) · 901 Bytes
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
import java.util.HashMap;
import java.util.Map;
public class TwoSum
{
Map<Integer, Integer> _map = new HashMap();
/** Initialize your data structure here. */
public TwoSum()
{
}
/** 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 );
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public boolean find( int value )
{
for ( int k : _map.keySet() )
{
if ( _map.containsKey( value - k ) )
{
if ( k * 2 == value && _map.get( k ) > 1 )
return true;
else if ( k * 2 != value )
return true;
}
}
return false;
}
}
/**
* Your TwoSum object will be instantiated and called as such:
* TwoSum obj = new TwoSum();
* obj.add(number);
* boolean param_2 = obj.find(value);
*/