Fast O(n) Java Solution


  • 0
    public class Solution {
        public int findPairs(int[] nums, int k) {
            if(k < 0) return 0;
            HashSet<Integer> numSet = new HashSet<Integer>();
            HashSet<Integer> resSet = new HashSet<Integer>();
            for(int i = 0; i < nums.length; ++i){
                int low = nums[i] - k;
                int high = nums[i] + k;
                if(numSet.contains(low)){
                    resSet.add(low);
                }
                if(numSet.contains(high)){
                    resSet.add(nums[i]);
                }
                numSet.add(nums[i]);
            }
            return resSet.size();
        }
    }
    

Log in to reply
 

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