Java O(n) Solution - one HashMap one Iteration


  • 0
    P
    public class Solution {
        public int findPairs(int[] nums, int k) {
            if (nums == null || nums.length == 0 || k < 0)   return 0;
            
            Map<Integer, Integer> map = new HashMap<>();
            int count = 0;
            for (int i : nums) {
                map.put(i, map.getOrDefault(i, 0) + 1);
                if((map.get(i) == 1) && k > 0)
                {
                    if(map.containsKey(i+k)){
                        count++;
                    }
                    if(map.containsKey(i-k)){
                        count++;
                    }
                }
               else if(k==0 && map.get(i)==2){
                    count++;
                }
            }
            
            return count;
        }
    
    
    ~~~

Log in to reply
 

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