Java, search (target - 0.5), (target + 0.5) instead using binary search


  • 0
    A
    public int[] searchRange(int[] nums, int target) {
            int left = helper(nums, target - 0.5);
            int right = helper(nums, target + 0.5);
            if(left == right) {
                return new int[] {-1, -1};
            } else {
                return new int[] {left, right - 1};
            }
        }
        
        private int helper(int[] nums, double target) {
            int low = 0, high = nums.length - 1, mid = low + (high - low) / 2;
            while ( low <= high) {
                mid = low + (high - low) / 2;
                if (nums[mid] < target) {
                    low = mid + 1;
                } else {
                     high = mid - 1;
                }
            }
            return low;
        }

Log in to reply
 

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