|
| 1 | +# 34. Find First and Last Position of Element in Sorted Array |
| 2 | +https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array |
| 3 | +Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. |
| 4 | + |
| 5 | +If target is not found in the array, return [-1, -1]. |
| 6 | + |
| 7 | +You must write an algorithm with O(log n) runtime complexity. |
| 8 | + |
| 9 | + |
| 10 | +Example 1: |
| 11 | +Input: nums = [5,7,7,8,8,10], target = 8 |
| 12 | +Output: [3,4] |
| 13 | + |
| 14 | +Example 2: |
| 15 | +Input: nums = [5,7,7,8,8,10], target = 6 |
| 16 | +Output: [-1,-1] |
| 17 | + |
| 18 | +Example 3: |
| 19 | +Input: nums = [], target = 0 |
| 20 | +Output: [-1,-1] |
| 21 | + |
| 22 | +Constraints: |
| 23 | +0 <= nums.length <= 10^5 |
| 24 | +-10^9 <= nums[i] <= 10^9 |
| 25 | +nums is a non-decreasing array. |
| 26 | +-10^9 <= target <= 10^9 |
| 27 | + |
| 28 | +``` python3 |
| 29 | +class Solution: |
| 30 | + def searchRange(self, nums: List[int], target: int) -> List[int]: |
| 31 | + def biSearch(nums, target): |
| 32 | + left, right = 0, len(nums) - 1 |
| 33 | + while left <= right: |
| 34 | + mid = (left + right) // 2 |
| 35 | + if nums[mid] >= target: |
| 36 | + right = mid - 1 |
| 37 | + else: |
| 38 | + left = mid + 1 |
| 39 | + return left |
| 40 | + a = biSearch(nums, target) |
| 41 | + b = biSearch(nums, target + 1) |
| 42 | + if a == len(nums) or nums[a] != target: |
| 43 | + return [-1, -1] |
| 44 | + else: |
| 45 | + return [a, b - 1] |
| 46 | +``` |
0 commit comments