O(n) with one HashMap


  • 1
    P
        public int findPairs(int[] nums, int k) {
            if ((nums == null) || (nums.length < 1) || (k < 0)) {
                return 0;
            }
    
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    
            int count = 0;
            for (int i = 0; i < nums.length; i++) {
    
                int currentNum = nums[i];
                if ((k == 0) && (map.containsKey(currentNum) && (map.get(currentNum) == 1))) {
                    count++;
                } else if (!map.containsKey(currentNum)) {
                    if (map.containsKey(currentNum + k)) {
                        count++;
                    }
                    if (map.containsKey(currentNum - k)) {
                        count++;
                    }
                    if (!map.containsKey(currentNum)) {
                        map.put(currentNum, 0);
                    }
                }
                map.put(currentNum, map.get(currentNum) + 1);
    
            }
            return count;
        }
    
    

  • 0
    C

    Simplified some.

    public class Solution {
        public int findPairs(int[] nums, int k) {
            if (k < 0) return 0;
            int count = 0;
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                if (k == 0 && map.getOrDefault(nums[i], 0) == 1) count++;
                else if (!map.containsKey(nums[i])) {
                    if (map.containsKey(nums[i] + k)) count++;
                    if (map.containsKey(nums[i] - k)) count++;
                }
                map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
            }
            return count;
        }
    }

Log in to reply
 

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