Interesting Java Solution/ HashSet Only


  • 7

    Put all numbers n in Hashset S1.
    Put all numbers n+k in HashSet S2.
    The number of pairs are the intersection of the two Hashsets. Different conditions apply to k=0 or k<0.

    public class Solution {
        public int findPairs(int[] nums, int k) {
            
            int ans = 0;
            
            if(k<0) return ans;
            
            Set<Integer> set1 = new HashSet<Integer> ();
            Set<Integer> set2 = new HashSet<Integer> ();
            
            if(k==0){
                    for(int n:nums){
                        if(!set1.contains(n))
                            {set1.add(n);}
                        else{
                            set1.remove(n);
                            if(!set2.contains(n)) ans++;
                            set2.add(n);
                            }
                    }
            }
            else{
                for(int n:nums){
                    set1.add(n);
                    set2.add(n+k);
                }
                set1.retainAll(set2);
                ans = set1.size();
            }
            
            return ans;
        }
    }
    

  • 0
    G

    @wangdi814 Good Job Xuejie! 666


  • 0

    Interesting point, tks for sharing.


  • 0
    Q

    @wangdi814 Brilliant idea!
    But set1.remove(n) seems unnecessary.


Log in to reply
 

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