Java Straightforward Method


  • 0
    Z
    public class Solution {
        public int findPairs(int[] nums, int k) {
            if (k < 0) return 0;
            Map<Integer, Integer> map = new HashMap<>();
            for (int num : nums) {
                map.put(num, map.getOrDefault(num, 0)+1);
            }
            Set<String> set = new HashSet<>();
            int cnt = 0;
            for (int num : nums) {
                if (k == 0) {
                    if (map.get(num) > 1 && set.add(num+":"+num)) cnt++;
                } else {
                    if (map.containsKey(num-k) && set.add(num-k+":"+num)) cnt++;
                }
            }
            return cnt;
        }
    }
    

Log in to reply
 

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