30 ms straightforward Java O(n) solution using one HashMap


  • 0
    Q

    Entry in the HashMap use distinct number from the input array as key and a Boolean value to indicate whether pair (key, key + k) has already recorded.

    public int findPairs(int[] nums, int k) {
            if(k < 0) return 0;
            int answer = 0;
            Map<Integer, Boolean> tmp = new HashMap();
            for(int i = 0; i < nums.length; i++) {
            	if(tmp.containsKey(nums[i] - k) && tmp.get(nums[i] - k) == false) {
                	        answer++;
            		tmp.put(nums[i] - k, true);//pair (nums[i] - k, nums[i]) is found
            	}
            	if(!tmp.containsKey(nums[i]) && tmp.containsKey(nums[i] + k)) {
            		answer++;
            		tmp.put(nums[i], true);//pair (nums[i], nums[i] + k) is found
            	}
            	if(!tmp.containsKey(nums[i])) tmp.put(nums[i], false); //pair (nums[i], nums[i] + k) is not found
            }
            return answer;
        }
    

Log in to reply
 

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