Java, Two pointer approach, beats 90%


  • 0
    N
    1. sort array,
    2. use left, right two pointers
    public class Solution {
        public int findPairs(int[] nums, int k) {
            
            Arrays.sort(nums);
            
            int l = 0;
            int r = 1;
            int count = 0;
            
            if (k < 0) {
                return count;
            }
            while (l < nums.length && r < nums.length) {
                if (l == r) {
                    r++;
                    continue;
                }
                
                if (nums[r] - nums[l] == k) {
                    count++;
                    l++;
                    while (l < nums.length && nums[l] == nums[l - 1]) {
                        l++;
                    }
                    r++;
                    while (r < nums.length && nums[r] == nums[r - 1]) {
                        r++;
                    }
                }
                else if (nums[r] - nums[l] < k) {
                    r++;
                    while (r < nums.length && nums[r] == nums[r - 1]) {
                        r++;
                    }
                }
                else {
                    l++;
                    while (l < nums.length && nums[l] == nums[l - 1]) {
                        l++;
                    }
                }
            }
            
            return count;
        }
    }

Log in to reply
 

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