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
addmethod, 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
findmethod, we loop through the HashMap keyset’s every numbernum, thetargetwill bevalue - num. Then we check if the hashmap contains thetarget, then we need to consider two cases. The first case is if thetargetis equal to the current number and the frequency of that number is 1, then wecontinue. The second case is if thetargetis not equal to the current number, that means we find a pair that sum tovalueso we returntrue. At the end when we loop through all the number, then we returnfalse.
Solution
1 | |