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

二分找最左端,再二分找最右端。

 1 class Solution {
 2 public:
 3     int findPos(int a[], int beg, int end, int key, bool findLeft)
 4     {
 5         if (beg > end)
 6             return -1;
 7             
 8         int mid = (beg + end) / 2;
 9         
10         if (a[mid] == key)
11         {
12             int pos = findLeft ? findPos(a, beg, mid - 1, key, findLeft) : findPos(a, mid + 1, end, key, findLeft);
13             return pos == -1 ? mid : pos;
14         }
15         else if (a[mid] < key)
16             return findPos(a, mid + 1, end, key, findLeft);
17         else
18             return findPos(a, beg, mid - 1, key, findLeft);       
19     }
20     
21     vector<int> searchRange(int A[], int n, int target) {
22         // Start typing your C/C++ solution below
23         // DO NOT write int main() function
24         int leftPos = findPos(A, 0, n - 1, target, true);
25         int rightPos = findPos(A, 0, n - 1, target, false);
26         
27         vector<int> ret;
28         
29         ret.push_back(leftPos);
30         ret.push_back(rightPos);
31         return ret;
32     }
33 };
posted @ 2012-11-14 16:30  chkkch  阅读(3098)  评论(0编辑  收藏  举报