Java: Note fast but only map needed


  • 0

    Those submissions may want to accelerate. So they use another set or list. I provide a solution for one map.

    Your runtime beats 81.89 % of java submissions.
    Runtime: 249 ms

    class TwoSum {
        /** Initialize your data structure here. */
        HashMap<Integer, Integer> map;
        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 (int i : map.keySet()) {
                int j = value - i;
                if ((i == j && map.get(i) > 1 )|| (i != j && map.containsKey(j))) {
                    return true;
                }
            }
            return false;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.