Share my Java solution


  • 0
    A
    public class Solution {
        public int findPairs(int[] nums, int k) {
            if(nums == null || nums.length < 2) return 0;
            int count = 0;
            Arrays.sort(nums);
            int j = 1;
            for(int i = 0;i<nums.length;i++){
                if(i ==0 || nums[i]!=nums[i-1]){
                    j = i+1;
                    while(j<nums.length && nums[i]+k>nums[j]){
                        j++;
                    }
                    if(j<nums.length && nums[i]+k == nums[j])count++;
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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