Clean O(N) Java Code


  • 0
    A
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    
    public void add(int number) {
    	map.put(number, map.getOrDefault(number, 0) + 1);
    }
    
    public boolean find(int value) {
    	for (Integer key : map.keySet()) {
    		if (key * 2 == value) {
    			if (map.containsKey(key) && map.get(key) > 1)
    				return true;
    		} else {
    			if (map.containsKey(value - key))
    				return true;
    		}
    	}
    	return false;
    }

Log in to reply
 

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