170. 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.

Example 1:

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

Example 2:

add(3); add(1); add(2);
find(3) -> true
find(6) -> false

用hashmap存新加入的元素和频率

add直接把元素加进hashmap。find遍历整个map,分两种情况,如果k和v相同,对应频率要大于1;如果不同,只要map中存在key=v即可。

时间:add - O(1), find - O(N),空间:O(N)

class TwoSum {
    HashMap<Integer, Integer> map;

    /** Initialize your data structure here. */
    public TwoSum() {
        map = new HashMap<>();
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        map.put(number, map.getOrDefault(number, 0) + 1);
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
            int k = entry.getKey();
            int v = value - k;
            if((k != v && map.containsKey(v)) || (k == v && map.get(v) > 1))
                return true;
        }
        return false;
    }
}

/**
 * Your TwoSum object will be instantiated and called as such:
 * TwoSum obj = new TwoSum();
 * obj.add(number);
 * boolean param_2 = obj.find(value);
 */
原文地址:https://www.cnblogs.com/fatttcat/p/10050186.html