Two Sum III - Data structure design

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,

  1. add(1); add(3); add(5);
  2. find(4) -> true
  3. find(7) -> false

Solution:

  1. public class TwoSum {
  2. private HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
  3. public void add(int number) {
  4. if (map.containsKey(number)) {
  5. map.put(number, map.get(number) + 1);
  6. } else {
  7. map.put(number, 1);
  8. }
  9. }
  10. public boolean find(int value) {
  11. for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
  12. int key = entry.getKey();
  13. int idx = entry.getValue();
  14. int val = value - key;
  15. if (key != val && map.containsKey(val)) {
  16. return true;
  17. }
  18. if (key == val && map.get(key) > 1) {
  19. return true;
  20. }
  21. }
  22. return false;
  23. }
  24. }