O(n logn) Java Solution


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

Log in to reply
 

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