TheAlgorithms-Python/data_structures/arrays/search_range.py

57 lines
1.3 KiB
Python
Raw Normal View History

2023-10-09 12:15:24 +08:00
"""
Problem: Find First and Last Position of Element in Sorted Array
Description:
2023-10-09 12:25:05 +08:00
Given an array of integers nums sorted in non-decreasing order,
2023-10-09 12:15:24 +08:00
find the starting and ending position of a given target value.
If target is not found in the array, return [-1, -1].
2023-10-09 12:25:05 +08:00
Leetcode ref:
2023-10-09 12:15:24 +08:00
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
"""
2023-10-09 12:25:05 +08:00
2023-10-09 12:25:05 +08:00
def search_range(nums: list[int], target: int) -> list[int]:
"""
2023-10-09 12:58:36 +08:00
>>> search_range([5,7,7,8,8,10],8)
[3, 4]
2023-10-09 12:58:36 +08:00
>>> search_range([5,7,7,8,8,10],6)
[-1, -1]
2023-10-09 12:58:36 +08:00
>>> search_range([],3)
[-1, -1]
2023-10-09 12:58:36 +08:00
>>> search_range([5,7,8,9,9],7)
[1, 1]
"""
2023-10-09 13:02:08 +08:00
def binary_search(nums:list, target:int, left:int):
low, high = 0, len(nums) - 1
index = -1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
index = mid
if left:
high = mid - 1
2023-10-09 12:15:24 +08:00
else:
low = mid + 1
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return index
2023-10-09 12:15:24 +08:00
left_index = binary_search(nums, target, left=True)
right_index = binary_search(nums, target, left=False)
2023-10-09 12:15:24 +08:00
return [left_index, right_index]
2023-10-09 12:15:24 +08:00
if __name__ == "__main__":
from doctest import testmod
testmod()