class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target)
{
vector<int> r(, -);
if (!nums.size())
{
return r;//为空时,返回[-1,-1]
}
int l = , h = nums.size() - , m = ;
if (target < nums[l] || nums[h] < target)
{
return r; //小于最小或大于最大返回[-1,-1]
}
while (l <= h)
{
m = (l + h) / ;
if (nums[m] == target)
{
//命中m时
int i = m;
while (nums[i] == target&&i < nums.size())
{
i++;//寻找nums中与target相等值的右界
}
r[] = i - ;
while (nums[m] == target&&m >= )
{
m--;//寻找nums中与target相等值的左界
}
r[] = m + ;
return r;
}
else if (nums[m] < target)
{
l = m + ;
}
else
{
h = m - ;
}
}
return r;//没找到target,返回[-1,-1]
}
};
补充一个python的实现:
class Solution:
def searchRange(self, nums: 'List[int]', target: 'int') -> 'List[int]':
n = len(nums)
i =
j = n -
if i == j:
if nums[i] == target:
return [,]
else:
return [-,-]
begin =
end = n -
while i < j:
if nums[i] == target:
begin = i
end = i
while end < n and nums[end] == target:
end +=
return [begin,end-]
if nums[j] == target:
end = j
begin = j
while begin >= and nums[begin] == target:
begin -=
return [begin+,end]
mid = i + (j - i) //
if nums[mid] == target:
begin = mid
while begin >= and nums[begin] == target:
begin -=
end = mid
while end < n and nums[end] == target:
end +=
return [begin+,end-]
elif nums[mid] < target:
i = mid +
else:
j = mid -
return [-,-]