首页 > 其他 > 详细

Leetcode 34. Search for a Range

时间:2016-07-23 23:04:32      阅读:397      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!