Simple Java O(n) with single For-loop & single HashMap


  • 4
    L

    Solved it by One For-loop and One HashMap

    public int findPairs(int[] nums, int k) {
        if(k < 0) return 0;
        Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
        int ret = 0;
        for(int n : nums){
            /* if smaller matched value exists */
            if(map.containsKey(n-k) && !map.get(n-k)){
                map.put(n-k,true);
                ret++;
            }
            /* if larger matched value exists */
            if(map.containsKey(n+k) && (!map.containsKey(n) || !map.get(n))){
                map.put(n, true);
                ret++;
            }
            /* if current value has not yet been added*/
            if(!map.containsKey(n)){
                map.put(n, false);
            }
        }
        return ret;
    }
    

Log in to reply
 

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