O(n) clean Java solution, one Hashmap


  • 0
    public int findPairs(int[] nums, int k) {
        if(k<0) return 0;
        int result = 0;
        HashMap<Integer,Integer> set = new HashMap<Integer,Integer>();
        for(int integer: nums){
            if(!set.containsKey(integer)){
                if(set.containsKey(integer-k)) result++;
                if(set.containsKey(integer+k)) result++;
                set.put(integer,0);
            }
            else if(k==0&&set.get(integer)==0) {
                    result++;
                    set.put(integer,1);
            }
        }
        return result;
    }

Log in to reply
 

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