532. K-diff Pairs in an Array

    xiaoxiao2021-03-25  116

    Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

    1,首先想到hashSet去重复,但是有k=0的情况,所以不适用

    2,用hashMap,k=0,value>=2,避免反复出现[i,i,i,i]的情况

    public class Solution { public int findPairs(int[] nums, int k) { if(nums.length == 0 ||nums == null || k < 0) return 0; int m = 0; Map<Integer, Integer> map = new HashMap<>(); for(int c: nums) { if(map.containsKey(c)) { map.put(c, map.get(c) + 1); } else { map.put(c, 1); } } for(Map.Entry<Integer, Integer> entry: map.entrySet()) { if(k == 0) { if(entry.getValue() >= 2) { m++; } } else { if(map.containsKey(entry.getKey() + k)) { m++; } } } return m; } }

    1,首先想到hashSet去重复,但是有k=0的情况,所以不适用

    2,用hashMap,k=0,value>=2,避免反复出现[i,i,i,i]的情况

    转载请注明原文地址: https://ju.6miu.com/read-7364.html

    最新回复(0)