Problem
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 1:
1 |
|
Example 2:
1 |
|
Explanation
-
In the
add
method, We can use a HashMap to record the frequency of the added number. The key is the number, the value is the frequency. -
In the
find
method, we loop through the HashMap keyset’s every numbernum
, thetarget
will bevalue - num
. Then we check if the hashmap contains thetarget
, then we need to consider two cases. The first case is if thetarget
is equal to the current number and the frequency of that number is 1, then wecontinue
. The second case is if thetarget
is not equal to the current number, that means we find a pair that sum tovalue
so we returntrue
. At the end when we loop through all the number, then we returnfalse
.
Solution
1 |
|