码迷,mamicode.com
首页 > 其他好文 > 详细

Search for a Range <leetcode>

时间:2014-09-17 13:31:02      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   os   ar   for   div   art   

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 };

 

Search for a Range <leetcode>

标签:style   blog   color   io   os   ar   for   div   art   

原文地址:http://www.cnblogs.com/sqxw/p/3976814.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!