My Simple Solution in Java using two set approach (Very Fast)


  • 0
    S

    Duplicate set is used if k = 0, other than that pretty self explanatory.. Please give your inputs

    public int findPairs(int[] nums, int k) {
            if(k<0) return 0;
            
            Set<Integer> set = new HashSet<>();
            Set<Integer> dupSet = new HashSet<>();
            
            int count = 0;
    
            for(int i=0; i<nums.length; i++){
                if(!set.contains(nums[i])) 
                    set.add(nums[i]);
                else
                    dupSet.add(nums[i]);
            }
            
            if(k==0) return dupSet.size();
            
            Iterator<Integer> iterator = set.iterator();
            
            while(iterator.hasNext()){
                if(set.contains(iterator.next() + k)) count++;
            }
            
            return count;
        }
    

Log in to reply
 

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