yokostan / Leetcode-Solutions

Doing exercise on Leetcode. Carry on!
0 stars 3 forks source link

Leetcode #170 Two Sum III - Data Structure #206

Open yokostan opened 5 years ago

yokostan commented 5 years ago
class TwoSum {
    private HashMap<Integer, Integer> map = new HashMap<>();

    /** Initialize your data structure here. */
    public TwoSum() {

    }

    /** 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 (int num : map.keySet()) {
            if (map.containsKey(value - num) && (value - num != num || map.get(value - num) >= 2)) {
                return true;
            }
        }

        return false;
    }
}