Two Pointers, easy to understand.


  • 0
    Z
    public int findPairs(int[] nums, int k) {
        Arrays.sort(nums);
        int left  = 0; 
        int right = 1;
        int count = 0;
        while (left <= right && right < nums.length) {
            if (nums[right] - nums[left] < k) {
                right++;
            } else if (nums[right] - nums[left] > k) {
                left++;
            } else {
                count++;
                right++;
                while (right < nums.length && nums[right - 1] == nums[right]) {
                    right++;
                }
                while (left <  nums.length - 1 && nums[left + 1] == nums[left]) {
                    left++;
                }
            }
            if (left == right) {
                right++;
            }
        }
        
        return count++;
    }

Log in to reply
 

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