Frank's Java solution - binary search


  • 0
    F
    class Solution {
        int binarySearch(int[] nums, int l, int r, int value) {
            while (l<=r && l<nums.length) {
                int mid = (l+r)/2;
                if (nums[mid] > value) {
                    r = mid-1;
                } else if (nums[mid] < value) {
                    l = mid+1;
                } else {
                    return mid;
                }
            }
            return -1;
        }
        public int findPairs(int[] nums, int k) {
            int count = 0;
            Arrays.sort(nums);
            for (int i=0; i<nums.length; i++) {
                if (i==0 || nums[i-1] != nums[i]) {
                    int m = binarySearch(nums, i+1, nums.length-1, nums[i]+k);
                    if (m > 0) {
                        count++;
                    }
                }
            }
            return count;
        }
    }
    

Log in to reply
 

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