Java Solution using hashmap or hashset


  • 0
    F
    public class Solution {
        public int findPairs(int[] nums, int k) {
            return findPairsHash(nums, k);        
        }
        
        private int findPairsHash(int[] nums, int k) {
            int cnt = 0;
            
            if(k == 0) {
                Map<Integer, Integer> map = new HashMap<>();
            
                for(int num:nums) {
                    Integer freq = map.get(num);
                    if(freq!=null && freq==1) {
                        cnt++;
                    }
                    map.put(num, freq==null?1:freq+1);
                }
            } else if(k > 0) {
                Set<Integer> set = new HashSet<>();
                
                for(int num:nums) {
                    if(!set.contains(num)) {
                        cnt += (set.contains(num+k)?1:0)+(set.contains(num-k)?1:0);
                        set.add(num);
                    }
                }
            }
            
            return cnt;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.