首页 > 其他 > 详细

LeetCode - Refresh - Search for a Range

时间:2015-03-23 14:47:01      阅读:189      评论:0      收藏:0      [点我收藏+]

Actually, we are searching the right end of the target so:

1. start could be same as end

2. A[mid] > target, shift to left

3. A[mid] <= target shift to right

 1 class Solution {
 2 public:
 3     int bsearch(int A[], int start, int end, int target) {
 4         int index = -1, mid = 0;
 5         while (start <= end) {
 6             mid = (start + end)/2;
 7             if (A[mid] <= target) {
 8                 start = mid + 1;
 9                 index = mid;
10             } else {
11                 end = mid - 1;
12             }
13         }
14         return index;
15     }
16     vector<int> searchRange(int A[], int n, int target) {
17         vector<int> result(2, -1);
18         result[0] = bsearch(A, 0, n-1, target-1) + 1;
19         result[1] = bsearch(A, 0, n-1, target);
20         if (result[0] == -1 || A[result[0]] != target) {
21             return vector<int> (2, -1);
22         }
23         return result;
24     }
25 };

 

LeetCode - Refresh - Search for a Range

原文:http://www.cnblogs.com/shuashuashua/p/4359497.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!