Java solution


  • 1
    T
    public class Solution {
        public int findPairs(int[] nums, int k) {
            // If k is less than 0, then return 0;
            if (k < 0) {
                return 0;
            }
            // Initialize a new hashMap and use the numbers in the array as key, and use a boolean to represent if the number has appeared before
            HashMap<Integer, Boolean> map = new HashMap<Integer, Boolean>();
            int count = 0;
            for (int i = 0; i < nums.length; i++) {
                
                if (map.containsKey(nums[i])) {
                    if (k == 0 && map.get(nums[i])) {
                        count++;
                    }
                    map.put(nums[i], false);
                }
                else {
                    int left = nums[i] - k;
                    int right = nums[i] + k;
                    int leftCount = map.containsKey(left) ? 1 : 0;
                    int rightCount = map.containsKey(right) ? 1 : 0;
                    count += leftCount + rightCount;
                    map.put(nums[i], true);
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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