LintCode-Search for a Range

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].

Example

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

Solution:

 

 1 public class Solution {
 2     /** 
 3      *@param A : an integer sorted array
 4      *@param target :  an integer to be inserted
 5      *return : a list of length 2, [index1, index2]
 6      */
 7     public ArrayList<Integer> searchRange(ArrayList<Integer> A, int target) {
 8         ArrayList<Integer> res = new ArrayList<Integer>();
 9         int start = -1, end = -1;
10         int p1 = 0, p2 = A.size()-1;
11         //find start point.
12         while (p1<=p2){
13             int mid = (p1+p2)/2;
14             
15             if (A.get(mid)==target){
16                 if (mid==0 || A.get(mid-1)!=target){
17                     start = mid;
18                     break;
19                 } else {
20                     p2 = mid-1;
21                 }
22             } else if (A.get(mid)>target)
23                 p2 = mid-1;
24             else p1 = mid+1;
25         }
26         
27         //find end point.
28         p1 = 0;
29         p2 = A.size()-1;
30         while (p1<=p2){
31             int mid = (p1+p2)/2;
32             
33             if (A.get(mid)==target){
34                 if (mid==A.size()-1 || A.get(mid+1)!=target){
35                     end = mid;
36                     break;
37                 } else p1 = mid+1;
38             } else if (A.get(mid)>target)
39                 p2 = mid-1;
40             else p1 = mid+1;
41         }
42         
43         res.add(start);
44         res.add(end);
45         
46         return res;
47     }
48 }

 

 

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值