Leetcode-Search for a range

本文介绍了一种算法,能够在已排序的整数数组中找到给定目标值的起始和结束位置,采用两次二分查找来确定左右边界,确保了算法的时间复杂度为O(logn)。

Given a sorted array of integers, 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].

For example,
Given [5, 7, 7, 8, 8, 10] and target value 8,
return [3, 4].

Have you met this question in a real interview?
 
Analysis:
We need to do two binary search. The first finds out the left boundary and the second finds out the right boundary.
if mid==target, we then check whether mid-1==target, if yes, we then continue to search [start,mid-1] until we find the left boundary.
Solution:
 1 public class Solution {
 2     public int[] searchRange(int[] A, int target) {
 3         int[] res = new int[]{-1,-1};
 4         if (A.length==0) return res;
 5 
 6         int start = 0, end = A.length-1;       
 7       
 8         //Find left range.
 9 
10         while (start<=end){
11             int mid = (start+end)/2;
12             if (A[mid]==target){
13                 //find right range also.
14                 if (mid+1==A.length || A[mid+1]!=target) res[1] = mid;
15                
16                 //Check left
17                 if (mid-1==-1 || A[mid-1]!=target){
18                     res[0]=mid;
19                     break;
20                 } else {
21                     end = mid-1;
22                     continue;
23                 }
24             } else if (A[mid]>target) end = mid-1;
25             else start = mid+1;
26         }
27 
28         if (start>end) return res;
29         if (res[0]!=-1 && res[1]!=-1) return res;
30 
31         //Find right
32         start = 0;
33         end = A.length-1;
34         while (start<=end){
35             int mid = (start+end)/2;
36             if (A[mid]==target){
37                 //Check right
38                 if (mid+1==A.length || A[mid+1]!=target){
39                     res[1]=mid;
40                     break;
41                 } else {
42                     start = mid+1;
43                     continue;
44                 }
45             } else if (A[mid]>target) end = mid-1;
46             else start = mid+1;
47         }
48 
49         return res;        
50     }
51 }

 

转载于:https://www.cnblogs.com/lishiblog/p/4111920.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值