没看答案,考察的是有重复数字数组的二分查找的左右边界问题。
python
class Solution:
def left_bound(self, nums, target):
left, right = 0, len(nums)-1
while left <= right:
mid = int(left + (right - left)/2)
if nums[mid] == target:
right = mid - 1
elif nums[mid] < target:
left = mid + 1
elif nums[mid] > target:
right = mid - 1
if left >= len(nums) or nums[left] != target:
return -1
return left
def right_bound(self, nums, target):
left, right = 0, len(nums)-1
while left <= right:
mid = int(left + (right - left)/2)
if nums[mid] == target:
left = mid + 1
elif nums[mid] < target:
left = mid + 1
elif nums[mid] > target:
right = mid - 1
if right < 0 or nums[right] != target:
return -1
return right
def searchRange(self, nums: List[int], target: int):
res = []
res.append(self.left_bound(nums, target))
res.append(self.right_bound(nums, target))
return res
c++
class Solution {
public:
vector<int> searchRange(vector<int>& nums, int target) {
int left_index = left_bound(nums, target);
int right_index = right_bound(nums, target);
return {left_index, right_index};
}
int left_bound(vector<int>& nums, int& target) {
// 找左边界
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
right = mid - 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
}
}
if (left < 0 || left >= nums.size()) return -1;
return nums[left] == target ? left : -1;
}
int right_bound(vector<int>& nums, int& target) {
// 找右边界
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] == target) {
left = mid + 1;
} else if (nums[mid] > target) {
right = mid - 1;
} else if (nums[mid] < target) {
left = mid + 1;
}
}
if (right < 0 || right >= nums.size()) return -1;
return nums[right] == target ? right : -1;
}
};