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

Leetcode 34. Search for a Range

时间:2016-07-23 23:07:47      阅读:357      评论:0      收藏:0      [点我收藏+]

标签:

34. Search for a Range

  • Total Accepted: 91570
  • Total Submissions: 308037
  • Difficulty: Medium

 

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(vector<int>& nums, int target) {
 4         int n=nums.size(),low=0,high=n-1,mid;
 5         vector<int> res;
 6         while(low<=high){
 7             mid=low+(high-low)/2;
 8             if(nums[mid]<target){
 9                 low=mid+1;
10             }
11             else{
12                 high=mid-1;
13             }
14         }
15         if(nums[low]==target){
16             res.push_back(low);
17             while(low<n&&nums[low]==target) low++;
18             res.push_back(low-1);
19         } 
20         else{
21             res.push_back(-1);
22             res.push_back(-1);
23         }
24         return res;
25     }
26 };

 

Leetcode 34. Search for a Range

标签:

原文地址:http://www.cnblogs.com/Deribs4/p/5699667.html

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