leetcoed 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.

这道题的意思是,输入一个整数数组和一个整数k,咱们须要找出数组中绝对值差正好为k的不重复的整数对儿数组

Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
这个例子中有两个不一样的整数对, (1, 3)和(3, 5).code

Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
这个例子里有四个不一样的整数对(1, 2), (2, 3), (3, 4)和(4, 5).get

Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
这个例子里有一个符合要求的整数对(1,1)hash

想法

  • 这道题我分两种状况进行的讨论,一种是k不为0的时候,我经过新建一个hashset来完成计算。
  • 因为hashset没法处理相同key的操做,所依对于k==0的时候,我采用了hashmap进行操做。
  • k为0时,对于每一次遍历,找到这个值是否已经存在在hashmap里,同时获取这个值出现过的次数(value)。若是次数为1,那么咱们得到了一个符合要求的整数对,若是次数大于1,那么说明这个整数对已经被统计过了,能够忽略。若是这个键值不曾出如今hashmap里,那么咱们将其存入hashmap,将value赋值为1.
  • 当k不为0时,咱们遍历每个元素,若是这个元素和当前set中的元素不重复的话,咱们将这个元素存入set,而后判断在set中是否有知足和这个元素的绝对值相差为k的整数出现,若是有,构成一个整数对。

解法

int res = 0;
        if(k < 0)return 0;
        if(k == 0){
            HashMap<Integer,Integer> countZero = new HashMap<Integer,Integer>();
            for(int i=0;i<nums.length;i++){
                if(countZero.containsKey(nums[i])){
                    if(countZero.get(nums[i]) == 1){
                        res ++;
                        countZero.put(nums[i], 2);
                    }
                }else{
                    countZero.put(nums[i], 1);    
                }
            }
        }else{        
            Set<Integer> count = new HashSet<Integer>();
            for(int num : nums){
                if(!count.add(num)){continue;}
                if(count.contains(num+k)){
                    res ++;
                } 
                if(count.contains(num-k)){
                    res ++;
                }
            }
            
        }
        return res;
相关文章
相关标签/搜索