二分搜索, 搜左右部分稍微有些不同 需要注意
class Solution: # @param {integer[]} nums # @param {integer} target # @return {integer[]} def searchRange(self, nums, target): left = self.findIndex(nums, target, "left", 0, len(nums)-1) if left == -1: return [-1,-1] right = self.findIndex(nums, target, "right", left, len(nums)-1) return [left, right] def findIndex(self, nums, target, model, left, right): if left > right: return -1 if left == right: if nums[left] == target: return left else: return -1 if model == "left": mid = (left + right) / 2 else: mid = (left + right + 1) / 2 if nums[mid] > target: right = mid - 1 elif nums[mid] < target: left = mid + 1 else: if model == "left": right = mid else: left = mid return self.findIndex(nums, target, model, left, right)
时间: 2024-10-18 20:50:29