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
|
public class TwoSumDataStructureDesign { private Map<Integer, Integer> map = new HashMap<Integer, Integer>(); public void add(int number) { int count = 1; if (map.containsKey(number)) { count += map.get(number); } map.put(number, count); } public boolean find(int value) { boolean result = false; for (int i : map.keySet()) { int left = value - i; if (i == left) { if (map.get(i) > 1) { result = true; } } else { result = map.containsKey(left); } if (result) { break; } } return result; } }
|