当前位置: 代码迷 >> 综合 >> 【Leetcode每日一题】34. 在排序数组中查找元素的第一个和最后一个位置(二分、lower_bound、upper_bound)
  详细解决方案

【Leetcode每日一题】34. 在排序数组中查找元素的第一个和最后一个位置(二分、lower_bound、upper_bound)

热度:39   发布时间:2023-11-23 11:57:48.0

Leetcode 每日一题
题目链接: 34. 在排序数组中查找元素的第一个和最后一个位置
难度: 中等
解题思路: 这道题题意很明显,就是二分查找。即为C++中的 lower_boundupper_bound 函数。这里给出python3的版本。
题解:

class Solution:def searchRange(self, nums: List[int], target: int) -> List[int]:if len(nums) == 0:return (-1, -1)# 向左二分def lower_bound(nums, target):l, r = 0, len(nums) - 1res = -1if l == r and target == nums[l]:return 0while l < r:mid = (l + r) // 2 # 向下取整if target <= nums[mid]:r = midres = midelse:l = mid + 1if res == -1 and target == nums[r]: # 右边界res = rif res != -1 and target != nums[res]: # 未找到res = -1return res# 向右二分def upper_bound(nums, target):l, r = 0, len(nums) - 1res = -1if l == r and target == nums[l]:return 0while l < r:mid = (l + r) // 2 + 1 # 向上取整if target < nums[mid]:r = mid - 1else:l = midres = midif res == -1 and target == nums[r]: # 左边界res = rif res != -1 and target != nums[res]: # 未找到res = -1return resreturn (lower_bound(nums, target),upper_bound(nums, target))