Two Sum III

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


 1 public class TwoSum {
 2     private HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
 3     /** Initialize your data structure here. */
 4     public TwoSum() {
 5         
 6     }
 7     
 8     /** Add the number to an internal data structure.. */
 9     public void add(int number) {
10         map.put(number, map.containsKey(number) ? map.get(number) + 1 : 1);
11     }
12     
13     /** Find if there exists any pair of numbers which sum is equal to the value. */
14     public boolean find(int value) {
15         for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
16             int base = entry.getKey();
17             int findMe = value - base;
18             
19             if ((base == findMe && map.get(base) >= 2) || 
20                  base != findMe && map.containsKey(findMe))
21                  return true;
22         }
23         return false;
24     }
25 }
26 
27 /**
28  * Your TwoSum object will be instantiated and called as such:
29  * TwoSum obj = new TwoSum();
30  * obj.add(number);
31  * boolean param_2 = obj.find(value);
32  */
原文地址:https://www.cnblogs.com/amazingzoe/p/6395334.html