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.

答案

class Solution {
    public int findPairs(int[] nums, int k) {
        if(k < 0) return 0;
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int num : nums) 
            map.put(num, (map.get(num) == null)? 1:map.get(num) + 1);
        int ans = 0;
        for(int num : map.keySet()) {
            Integer n = map.get(num);
            if(k == 0) {
                if(n > 1) ans++;
            }
            else {
                if(map.containsKey(num - k)) {
                    ans++;
                }
                /*
                You may search for num - k or num + k, but not both, otherwise you get duplicated pairs 
                if(map.containsKey(num + k)) {
                    ans++;
                }
                */
            }

        }
        return ans;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,449评论 0 10
  • 上班的路程是每天不能熬夜的理由,不得不提的是,三个月没有迟到记录,为此,我像是付出了生命的代价。 从流汗的夏天到渐...
    汤姆里德尔阅读 458评论 0 2
  • NLP 几大任务 自然语言处理(简称NLP),是研究计算机处理人类语言的一门技术,包括: 句法语义分析:对于给定的...
    hxiaom阅读 424评论 0 1
  • 热身 硬拉 40kg(2*15+10)*12 热身 110kg*4 4组 90kg*8 4组 高位下拉 62k...
    shane911阅读 131评论 0 0