菱纱梦

导航

Search for a Range <leetcode>

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     vector<int> searchRange(int A[], int n, int target) {
 4         int l=findPos(A,0,n-1,target,true);
 5         int r=findPos(A,0,n-1,target,false);
 6         vector<int> result;
 7         result.push_back(l);
 8         result.push_back(r);
 9         return result;
10     }
11     int findPos(int a[],int beg,int end,int key,bool findLeft)
12     {
13         if(beg>end)   return -1;
14         int mid=(beg+end)/2;
15         if(a[mid]==key)
16         {
17             int pos=findLeft?findPos(a,beg,mid-1,key,findLeft):findPos(a,mid+1,end,key,findLeft);
18             return pos==-1?mid:pos;
19         }
20         else if(a[mid]<key)
21         {
22             findPos(a,mid+1,end,key,findLeft);
23         }
24         else if(a[mid]>key)
25         {
26             findPos(a,beg,mid-1,key,findLeft);
27         }
28     }
29 };

 

posted on 2014-09-17 12:04  菱纱梦  阅读(153)  评论(0编辑  收藏  举报