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

leetcode 34. Search for a Range

时间:2015-02-05 23:20:04      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

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

[Solution]

二分法,A[middle] == target时向左右延伸,其他情况和二分法一致.

 1 vector<int> searchRange(int A[], int n, int target) 
 2     {
 3         int left = 0, right = n - 1, middle = (left + right) / 2;
 4         vector <int> range(2, -1);
 5         
 6         while (left <= right)
 7         {
 8             middle = (left + right) / 2;
 9             if (A[middle] == target)
10             {
11                 left = middle - 1;
12                 right = middle + 1;
13                 while (left >= 0 && A[left] == target)
14                     left--;
15                 while (right < n && A[right] == target)
16                     right++;
17                 break;
18             }
19             if (A[middle] < target)
20                 left = middle + 1;
21             else
22                 right = middle - 1;
23         }
24         
25         if (left <= right) 
26         {
27             range[0] = left + 1;
28             range[1] = right - 1;
29         }
30         return range;
31     }

 

leetcode 34. Search for a Range

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4276057.html

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