leetcode: Search for a Range

http://oj.leetcode.com/problems/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].

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

思路

先用二分法找到target出现的位置,然后不停的用二分法确定左右区间。

 1 class Solution {
 2 public:
 3     int binarySearch(int A[], int start, int end, int target) {
 4         while (start <= end) {
 5             int mid = (start + end) / 2;
 6             
 7             if (A[mid] == target) {
 8                 return mid;
 9             }
10             else if (A[mid] < target) {
11                 start = mid + 1;
12             }
13             else {
14                 end = mid - 1;
15             }
16         }
17         
18         return -1;
19     }
20 
21     
22     vector<int> searchRange(int A[], int n, int target) {
23         vector<int> result(2, -1);
24         int pos = binarySearch(A, 0, n - 1, target);
25         
26         if (-1 == pos) {
27             return result;
28         }
29         
30         int tmp_pos, start = pos, end = pos;
31         
32         tmp_pos = pos - 1;
33         
34         while (tmp_pos >= 0) {
35             tmp_pos = binarySearch(A, 0, tmp_pos, target);
36             
37             if (-1 == tmp_pos) {
38                 break;
39             }
40             else {
41                 start = tmp_pos;
42                 --tmp_pos;
43             }
44         }
45         
46         tmp_pos = pos + 1;
47         
48         while (tmp_pos < n) {
49             tmp_pos = binarySearch(A, tmp_pos, n - 1, target);
50             
51             if (-1 == tmp_pos) {
52                 break;
53             }
54             else {
55                 end = tmp_pos;
56                 ++tmp_pos;
57             }
58         }
59         
60         result[0] = start;
61         result[1] = end;
62         
63         return result;
64     }
65 };

 

转载于:https://www.cnblogs.com/panda_lin/p/search_for_a_range.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值