[Leetcode]_34 Search for a Range

/**
*  Index: 34
*  Title: Search for a Range
*  Author: ltree98
**/

二分+前后遍历

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int l = 0, h = nums.size()-1;
int mid = (l+h)/2;

while(l <= h)   {
if(nums[mid] > target)  h = mid-1;
else if(nums[mid] < target) l = mid+1;
else    {
int start = mid-1, end = mid+1;
while(start >= 0 && nums[start] == target)  --start;
while(end < nums.size() && nums[end] == target)     ++end;
return {start+1, end-1};
}
mid = (l+h)/2;
}
return {-1, -1};
}
};

二分

class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int start, end;
int l, h, mid;

l = 0, h = nums.size()-1;
while(l < h)    {
mid = (l+h)/2;
if(target <= nums[mid]) h = mid;
else    l = mid+1;
}
start = l;

l = 0, h = nums.size()-1;
while(l < h)    {
mid = (l+h)/2;
if(target >= nums[mid]) l = mid+1;
else    h = mid;
}
end = l;

if(start == end)    return {-1, -1};
else    return {start, end-1};
}
};

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客