One HashSet Solution


  • 0
    S
    public class Solution {
        public int findPairs(int[] nums, int k) {
            Set<Integer> set = new HashSet<>();
            int count = 0;
            Arrays.sort(nums);
            if (k != 0) {
               for (int i=0; i<nums.length; i++) {
                    if (set.contains(nums[i]-k)) {
                        count ++;
                        set.remove(nums[i]-k);
                    } 
                    set.add(nums[i]);
                } 
            } else {
                for (int i=0; i<nums.length-1; i++) {
                    if (i==0 && nums[1]==nums[0]) count ++;
                    if (i!=0 && nums[i]==nums[i+1] && nums[i]!=nums[i-1])  count++;
                }
            }
            
            return count;
        }
    }
    

Log in to reply
 

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