Another O(n) solution using hashMap


  • 0
    L

    Use hashMap to keep unique pair

    public class Solution {
        public int findPairs(int[] nums, int k) {
            if(k<0) return 0;
            Map<Integer, Integer> map=new HashMap<Integer,Integer>();
            for(int n:nums){
                if(map.containsKey(n+k)){
                    map.put(n,n+k);
                }
                if(map.containsKey(n-k)){
                    map.put(n-k,n);
                }
                if(!map.containsKey(n)){
                    map.put(n,Integer.MAX_VALUE);
                }
                
            }
            int count=0;
            for(int key:map.keySet()){
                if(map.get(key)!=Integer.MAX_VALUE) count++;
            }
            return count;
            
        }
    }
    

Log in to reply
 

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