Simple lower-bound & upper-bound solution in Java, cost 0ms


  • 0
    B

    The solution uses two auxiliary functions, lower_bound and upper_bound, which find smallest & largest indexes of the number @target in the array @nums respectively.

    public class Solution {
    private int lower_bound(int[] nums, int target) {
        int low = 0, high = nums.length - 1;
        while(low < high) {
            int mid = low + (high - low) / 2;
            if(nums[mid] < target)
                low = mid + 1;
            else
                high = mid;
        }
        return nums[low] == target? low : -1;
    }
    private int upper_bound(int[] nums, int target) {
        int low = 0, high = nums.length - 1;
        while(low < high) {
            int mid = low + (high+1 - low) / 2;
            if(nums[mid] > target)
                high = mid - 1;
            else
                low = mid;
        }
        return nums[low] == target? low : -1;
    }
    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[2];
        result[0] = lower_bound(nums, target);
        result[1] = upper_bound(nums, target);
        return result;
    }
    

    }


Log in to reply
 

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