Java Two Pointers (beat 99%)


  • 0
    I
    public int findPairs(int[] nums, int k) {
        if(nums.length<2||k<0) return 0;
        Arrays.sort(nums);
        int i = 0;
        int j = 1;
        int count = 0;
        while(j<nums.length){
            if(nums[j] - nums[i]==k&&j!=i) {
                count++;
                i++;
                while(i<nums.length&&nums[i]==nums[i-1]) i++;
                j = Math.max(i, j) +1;
            }
            else if (nums[j] - nums[i]>k)i++;
            else j++;
        }
        return count;
    }

Log in to reply
 

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