Fixed exercise 81 and added 74
This commit is contained in:
parent
65e8af6bb7
commit
64cb9ea7ae
33
leetcode/74_search_a_2d_matrix.py
Normal file
33
leetcode/74_search_a_2d_matrix.py
Normal file
@ -0,0 +1,33 @@
|
||||
import pytest
|
||||
|
||||
|
||||
class Solution:
|
||||
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
|
||||
rows, cols = len(matrix), len(matrix[0])
|
||||
left, right = 0, rows * cols - 1
|
||||
while left <= right:
|
||||
mid = left + (right - left) // 2
|
||||
|
||||
val = matrix[mid // cols][mid % cols]
|
||||
if val == target:
|
||||
return True
|
||||
elif val < target:
|
||||
left = mid + 1
|
||||
else:
|
||||
right = mid - 1
|
||||
return False
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def solution():
|
||||
return Solution()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"matrix, target, expected",
|
||||
[([[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60]], 3, True)],
|
||||
)
|
||||
def test_search(
|
||||
solution: Solution, matrix: list[list[int]], target: int, expected: bool
|
||||
):
|
||||
assert solution.searchMatrix(matrix, target) == expected
|
@ -5,18 +5,20 @@ class Solution:
|
||||
def search(self, nums: list[int], target: int) -> bool:
|
||||
low, high = 0, len(nums) - 1
|
||||
while low <= high:
|
||||
breakpoint()
|
||||
mid = low + (high - low) // 2
|
||||
if nums[mid] == target:
|
||||
return True
|
||||
|
||||
while low < mid and nums[low] == nums[mid]:
|
||||
low += 1
|
||||
|
||||
if nums[mid] >= nums[low]:
|
||||
if nums[low] <= target <= nums[mid]:
|
||||
if nums[low] <= target < nums[mid]:
|
||||
high = mid - 1
|
||||
else:
|
||||
low = mid + 1
|
||||
else:
|
||||
if nums[mid] <= target <= nums[high]:
|
||||
if nums[mid] < target <= nums[high]:
|
||||
low = mid + 1
|
||||
else:
|
||||
high = mid - 1
|
||||
@ -32,8 +34,8 @@ def solution():
|
||||
@pytest.mark.parametrize(
|
||||
"nums, target, expected",
|
||||
[
|
||||
# ([2, 5, 6, 0, 0, 1, 2], 0, True),
|
||||
# ([2, 5, 6, 0, 0, 1, 2], 3, False),
|
||||
([2, 5, 6, 0, 0, 1, 2], 0, True),
|
||||
([2, 5, 6, 0, 0, 1, 2], 3, False),
|
||||
([1, 0, 1, 1, 1], 0, True),
|
||||
],
|
||||
)
|
||||
|
Loading…
x
Reference in New Issue
Block a user