34 Search for a Range

Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

Your algorithm's runtime complexity must be in the order of O(log n).

If the target is not found in the array, return [-1, -1].

Example 1:

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]

Example 2:

Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

已经排好了序,用二分查找。

重新实现 lower_bound 和 upper_bound

/**
 *
 * @author dongb
 * Search for a Range
 * rebuild the lower_bound and upper_bound
 * TC O(logn). SC O(1)
 * 
 */
public class Solution {
    public static int[] searchRange(int[] nums, int target) {
        int lower = lowerBound(nums, 0, nums.length, target);
        int upper = upperBound(nums, 0, nums.length, target);
        
        if (lower == nums.length || nums[lower] != target) {
            return new int[]{-1, -1};
        } else 
            return new int[]{lower, upper - 1};
    }
    
    public static int lowerBound(int[] nums, int first, int last, int target) {
        while(first != last) {
            int middle = first + (last - first) / 2;
            if (target > nums[middle]) {
                first = ++middle;
            } else {
                last = middle;
            }
        }
        return first;
    }
    
    public static int upperBound(int[] nums, int first, int last, int target) {
        while(first != last) {
            int middle = first + (last - first) / 2;
            if (target >= nums[middle]) {   // this is the only difference between lowerBound
                first = ++middle;
            } else {
                last = middle;
            }
        }
        return first;
    }
    
    public static void main(String args[]) {
        Scanner cin = new Scanner(System.in);
        int[] nums = new int[5];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = cin.nextInt();
        }
        int target = cin.nextInt();
        int[] answer = searchRange(nums, target);
        for (int i = 0; i < answer.length; i++) {
            System.out.println(answer[i]);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值