Java easy understand solution


  • 0
    O
    public class Solution {
        public int findPairs(int[] nums, int k) {
            int n = nums.length;
            if(n <= 1){
                return 0;
            }
            int count = 0;
            Arrays.sort(nums);
            for(int i = 0; i < n - 1; i++){
                if(i > 0 && nums[i] == nums[i-1]){
                    continue;
                }
                if(helper(nums, i + 1, nums[i] + k)){
                    count++;
                }
            }
            return count;
        }
        public boolean helper(int[]nums, int start, int target){
            int end = nums.length - 1;
            while(start + 1 < end){
                int mid = start + (end - start) / 2;
                if(nums[mid] == target){
                    return true;
                }else if(nums[mid] > target){
                    end = mid;
                }else{
                    start = mid;
                }
            }
            if(nums[start] == target){
                return true;
            }
            if(nums[end] == target){
                return true;
            }
            return false;
        }
    }
    

Log in to reply
 

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