LeetCode34 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].  (Medium)

分析:

标准的二分搜索题,找一个target的范围,也就是first position 元素等于target 和last position元素等于。

写两次二分搜索,注意中间start,end的变化情况的不同,一个为了保留住第一个满足条件的,一个为了保留住最后一个满足条件的。

代码:

 1 class Solution {
 2 public:
 3     vector<int> searchRange(vector<int>& nums, int target) {
 4         vector<int> result;
 5         if (nums.size() == 0) {
 6             return result;
 7         }
 8         int start = 0, end = nums.size() - 1;
 9         while (start + 1 < end) {
10             int mid = start + (end - start) / 2;
11             if (nums[mid] < target) {
12                 start = mid;
13             }
14             else {
15                 end = mid;
16             }
17         }
18         if (nums[start] == target) {
19             result.push_back(start);
20         }
21         else if (nums[end] == target) {
22             result.push_back(end);
23         }
24         
25         start = 0;
26         end = nums.size() - 1;
27         while (start + 1 < end) {
28             int mid = start + (end - start) / 2;
29             if (nums[mid] <= target) {
30                 start = mid;
31             }
32             else {
33                 end = mid;
34             }
35         }
36         if (nums[end] == target) {
37             result.push_back(end);
38         }
39         else if (nums[start] == target) {
40             result.push_back(start);
41         }
42         if (result.size() != 0) {
43             return result;
44         }
45         else {
46             return vector<int> {-1, -1};
47         }
48     }
49 };

 

 

 
posted @ 2016-08-23 20:43  wangxiaobao1114  阅读(161)  评论(0编辑  收藏  举报