Leetcode: 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,

add(1); add(3); add(5);

find(4) -> true

find(7) -> false

关键点在于对重复数字的处理,用hashmap存储值,然后判断value-num == num的情况下,count是否>=2.

 1 public class TwoSum {

 2     HashMap<Integer, Integer> map;

 3     public TwoSum() {

 4         map = new HashMap<Integer, Integer>();

 5     }

 6     

 7     public void add(int x) {

 8         if (map.containsKey(x)) {

 9             map.put(x, map.get(x)+1);

10         }

11         else {

12             map.put(x, 1);

13         }

14     }

15     

16     public boolean find(int target) {

17         for (int i : map.keySet()) {

18             if (map.containsKey(target-i)) {

19                 if (target - i != i) return true;

20                 else if (map.get(i) >= 2) return true;

21             }

22         }

23         return false;

24     }

25 }

注意17行的map.KeySet() return是一个Set形式的key的集合,Set是Collection的Subinterface, 所以这种for循环方法对Set也适用。而且即使key理论上是Integer, for循环前面的元素还是可以写成int:for(int i : map.keySet())

你可能感兴趣的:(LeetCode)