532-K-diff Pairs in an Array

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.

Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.

这道题不难,主要自己想多了。而且要注意细节

public class Solution {
    public int findPairs(int[] nums, int k) {
        if(k < 0) return 0;
        Map<Integer,Integer> map = new HashMap<>();
        int count = 0;
        for(int n : nums){
            map.put(n,map.getOrDefault(n,0) + 1);
        }
        for(int key : map.keySet()){
            int b = key + k;
            if(!map.containsKey(b)) continue;
            int n = map.get(b);
            int needN = (k == 0 ? 2 : 1);
            if(n >=needN){
                count++;
                map.put(key,1);
            }
        }
        return count;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 每日打卡。 来评论区记录下今天的收获和成长吧!
    树洞君阅读 194评论 6 1
  • 杨姐已经离开论坛了,杨姐告诉我,她已经正式退休! 与杨姐相识,可能有六七年了,也可能有七八年了。最初,她是论坛里的...
    黄晨昀阅读 237评论 0 0
  • 人说靠父母你是公主,致唯一把当做公主的爸爸。 小时候特别依赖爸爸,想要什么爸爸眼都不眨就给买,再晚想吃什么爸爸就去...
    婧萱只水眠阅读 166评论 0 1