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

[LeetCode] Search for a Range

时间:2015-08-15 18:10:48      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

The idea is to search for the left and right boundaries of target via two binary searches. Well, some tricks may be needed. Take a look at this link :-)

The code is rewritten as follows.

 1 class Solution {
 2 public:
 3     vector<int> searchRange(vector<int>& nums, int target) {
 4         int l = left(nums, target);
 5         if (l == -1) return {-1, -1};
 6         return {l, right(nums, target)};
 7     }
 8 private:
 9     int left(vector<int>& nums, int target) {
10         int n = nums.size(), l = 0, r = n - 1;
11         while (l < r) {
12             int m = l + ((r - l) >> 1);
13             if (nums[m] < target) l = m + 1;
14             else r = m;
15         }
16         return nums[l] == target ? l : -1;
17     }
18     int right(vector<int>& nums, int target) {
19         int n = nums.size(), l = 0, r = n - 1;
20         while (l < r) {
21             int m = l + ((r - l + 1) >> 1); 
22             if (nums[m] > target) r = m - 1;
23             else l = m;
24         }
25         return r;
26     }
27 }; 

 

[LeetCode] Search for a Range

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4732657.html

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