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

【leetcode】Search for a Range

时间:2015-01-24 15:46:00      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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     vector<int> searchRange(int A[], int n, int target) {
 4        
 5  
 6         vector<int>res(2);          
 7  
 8         res[0]=bs(A,n,target-1)+1;
 9         res[1]=bs(A,n,target);        
10   
11         if(res[1]==-1||A[res[1]]!=target)
12         {
13             res[0]=-1;
14             res[1]=-1;
15         }          
16         return res;
17     }
18    
19     //通过这个二分查找,如果有多个target的话可以找到最靠右边的元素
20     //同时也得注意,如果没有target则找到的是比target小的最大的最靠右元素
21      int bs(int A[],int n,int target)
22     {
23         int left=0;
24         int right=n-1;
25         int mid=(left+right)/2;
26         int ret=-1;
27        
28         while(left<=right)
29         {
30             if(A[mid]>target)
31             {
32                 right=mid-1;
33             }
34             else
35             {
36                 //只要是当前元素小于等于target,left就会右移,因此找到最靠右的元素
37                 ret=mid;
38                 left=mid+1;
39             }
40             mid=(left+right)/2;
41         }          
42         return ret;
43     }
44    
45 };

 

【leetcode】Search for a Range

标签:

原文地址:http://www.cnblogs.com/reachteam/p/4245958.html

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