From 64cb9ea7aec19564399ad56b5bffb55a9d2cf7ab Mon Sep 17 00:00:00 2001 From: strNophix Date: Wed, 31 Aug 2022 12:32:24 +0200 Subject: [PATCH] Fixed exercise 81 and added 74 --- leetcode/74_search_a_2d_matrix.py | 33 +++++++++++++++++++ .../81_search_in_rotated_sorted_array_ii.py | 12 ++++--- 2 files changed, 40 insertions(+), 5 deletions(-) create mode 100644 leetcode/74_search_a_2d_matrix.py diff --git a/leetcode/74_search_a_2d_matrix.py b/leetcode/74_search_a_2d_matrix.py new file mode 100644 index 0000000..dca7c34 --- /dev/null +++ b/leetcode/74_search_a_2d_matrix.py @@ -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 diff --git a/leetcode/81_search_in_rotated_sorted_array_ii.py b/leetcode/81_search_in_rotated_sorted_array_ii.py index c0a5056..651866f 100644 --- a/leetcode/81_search_in_rotated_sorted_array_ii.py +++ b/leetcode/81_search_in_rotated_sorted_array_ii.py @@ -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), ], )