LeetCode 34 - 二分查找

[JAVA]
看到题目要求时间复杂度为O(log n) 即考察二分查找,
对于sorted array:
只需要定义左边界left,右边界right,中点mid=left+(right-left)/2,

  while(left<=right){
      if(target==mid) return mid;   
      if target在左边[left,mid),则right=mid-1,重新开始二分查找;
      else 即target在右边(mid,right],则left=mid+1,重新开始二分查找;
  }

Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
要分别查找target的左边界和右边界,实现两个方法:
1.searchRightIndex()
2.searchLeftIndex()

class Solution {
    public int[] searchRange(int[] nums, int target) {
        int[] res={-1,-1};
        int right=searchRightIndex(nums,0,nums.length-1,target);
        if(right<0||nums[right]!=target)
            return res;
        res[0]=searchLeftIndex(nums,0,right,target);
        res[1]=right;
        return res;
    }
    public int searchRightIndex(int[] nums,int left,int right,int target){
        while(left<=right){
            int mid=left+(right-left)/2;
            if(nums[mid]>target) right=mid-1;
            else left=mid+1;
        }
        return right;
    }
    public int searchLeftIndex(int[] nums,int left,int right,int target){
        while(left<=right){
            int mid=left+(right-left)/2;
            if(nums[mid]<target) left=mid+1;
            else right=mid-1;
        }
        return left;
    }
}
//https://blog.csdn.net/happyaaaaaaaaaaa/article/details/50846000
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值