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;
相關文章
相關標籤/搜索