[Leetcode 89] 34 Search for a Range

寻找目标值区间
本文介绍了一种算法,用于在一个已排序的整数数组中查找给定目标值的起始和结束位置,该算法的时间复杂度为O(log n)。若未找到目标值,则返回[-1,-1];若找到目标值,则递归地搜索相同元素的前驱和后继,直至无法在左子数组或右子数组中找到更多相同的元素。

Problem:

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

 

Analysis:

The basic idea is first search for the existence of the target value. If not found, then just return {-1, -1}; If we found one in the given array, then we need to further search for whether there is same element preceeding it and sucseeding it. This procedure is recursive. Until we cannot further find element in the left subpart or right subpart, the result then is correct.

 

Code:

 1 class Solution {
 2 public:
 3     vector<int> searchRange(int A[], int n, int target) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         vector<int> res;
 7         int s = 0, e = n-1, l = -1, r = -1;
 8         
 9         while (s <= e) {
10             int m = (s + e) / 2;
11             
12             if (A[m] == target) {
13                 l = r = m;
14                 int old_l, old_r;
15                 while (l != -1) {
16                     old_l = l;
17                     l = search(A, s, l-1, target);
18                 }
19                     
20                 while (r != -1) {
21                     old_r = r;
22                     r = search(A, r+1, e, target);
23                 }
24                 
25                 l = old_l;
26                 r = old_r;
27                 break;
28             } else  if (A[m] > target)
29                 e = m-1;
30             else
31                 s = m+1;
32         }
33         
34         res.push_back(l);
35         res.push_back(r);
36         
37         return res;
38     }
39     
40 private:
41     int search(int A[], int s, int e, int t) {
42         while (s <= e) {
43             int m = (s+e) / 2;
44             
45             if (A[m] == t) {
46                 return m;
47             } else if (A[m] > t)
48                 e = m - 1;
49             else
50                 s = m + 1;
51         }
52         
53         return -1;
54     }
55 };
View Code

 

转载于:https://www.cnblogs.com/freeneng/p/3218919.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值