public class Solution { public int findPairs(int[] nums, int k) { HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0;i<nums.length;i++){ if(!map.containsKey(nums[i])){ map.put(nums[i],1); }else{ map.put(nums[i],map.get(nums[i])+1); } } int count=0; for(Map.Entry<Integer,Integer>entry:map.entrySet()){ if(k==0){ if(entry.getValue()>1){ count++; } }else{ if(k>0&&map.containsKey(entry.getKey()-k)){ count++; } } } return count; }}嗯,挺簡單的。。。大概就是用個hashmap記錄下每個數字,以及其出現的次數
再次遍歷數組,當出現nums [i]-k在map中存在的時候,就自加一,當然0要特殊處理,所以要保存存在的次數。。
有一個問題,就是感覺k<0的時候,{1,2,3,4,5} -1這個輸入的時候,明明應該是4是,畢竟比如1-2=-1嘛,但是結果是k<0認為其是0
攤手
新聞熱點
疑難解答