initial commit
This commit is contained in:
35
leetcode/33_search_in_rotated_array.py
Normal file
35
leetcode/33_search_in_rotated_array.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import pytest
|
||||
|
||||
|
||||
class Solution:
|
||||
def search(self, nums: list[int], target: int) -> int:
|
||||
# The first item of first ascending sequence is always bigger than the first item of the second ascending sequence.
|
||||
low, high = 0, len(nums) - 1
|
||||
while low <= high:
|
||||
mid = low + (high - low) // 2
|
||||
if nums[mid] == target:
|
||||
return mid
|
||||
|
||||
# If the current item is bigger than the first item of the first ascending sequence we know that nums[low:mid] is sorted.
|
||||
# Otherwise we know that the current mid is on the edge of the second ascending sequence.
|
||||
if nums[mid] >= nums[low]:
|
||||
if nums[low] <= target <= nums[mid]:
|
||||
high = mid - 1
|
||||
else:
|
||||
low = mid + 1
|
||||
else:
|
||||
if nums[mid] <= target <= nums[high]:
|
||||
low = mid + 1
|
||||
else:
|
||||
high = mid - 1
|
||||
|
||||
return -1
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def solution():
|
||||
return Solution()
|
||||
|
||||
|
||||
def test_search(solution: Solution):
|
||||
assert solution.search([4, 5, 6, 7, 0, 1, 2], 0) == 4
|
@@ -0,0 +1,47 @@
|
||||
import typing
|
||||
import pytest
|
||||
|
||||
FindFn = typing.Callable[[int], bool]
|
||||
|
||||
|
||||
class Solution:
|
||||
def searchRange(self, nums: list[int], target: int) -> list[int]:
|
||||
start = self.binary_search(nums, target, lambda v: v >= target)
|
||||
end = self.binary_search(nums, target, lambda v: v > target)
|
||||
return [start, end]
|
||||
|
||||
def binary_search(self, nums: list[int], target: int, fn: FindFn) -> int:
|
||||
res = -1
|
||||
low, high = 0, len(nums) - 1
|
||||
while low <= high:
|
||||
mid = low + (high - low) // 2
|
||||
if nums[mid] == target:
|
||||
res = mid
|
||||
|
||||
if fn(nums[mid]):
|
||||
high = mid - 1
|
||||
else:
|
||||
low = mid + 1
|
||||
|
||||
return res
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def solution():
|
||||
return Solution()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"nums, target, expected",
|
||||
[
|
||||
([5, 7, 7, 8, 8, 10], 8, [3, 4]),
|
||||
([5, 7, 7, 8, 8, 10], 6, [-1, -1]),
|
||||
([], 0, [-1, -1]),
|
||||
([1], 1, [0, 0]),
|
||||
([2, 2], 2, [0, 1]),
|
||||
],
|
||||
)
|
||||
def test_search_range(
|
||||
solution: Solution, nums: list[int], target: int, expected: list[int]
|
||||
):
|
||||
assert solution.searchRange(nums, target) == expected
|
Reference in New Issue
Block a user