Search a 2D Matrix II Solutions in Python
Number 240
Difficulty Medium
Acceptance 43.2%
Link LeetCode
Solutions
Python solution by haoel/leetcode
# Method 1: Binary Search on each row, if the first element of the row is already bigger than target, then skip# Time Complexity: O(mlogn)def searchMatrix1(self, matrix, target):def helper(low, high, row):while low <= high:mid = (low + high) // 2if matrix[row][mid] < target: low = mid + 1elif matrix[row][mid] > target: high = mid - 1else: return Truereturn Falseif not matrix or not matrix[0]: return Falsefor i in range(len(matrix)):if matrix[i][0] > target: return Falseelif matrix[i][0] == target: return Trueif helper(0, len(matrix[i]) - 1, i): return Truereturn False# Method 2: compare the element with top-right corner, and reduce the search range# Time complexity: O(m + n)def searchMatrix2(self, matrix, target):if not matrix or not matrix[0]: return Falserow, col = 0, len(matrix[0]) - 1while row < len(matrix) and col >= 0:if matrix[row][col] > target: col -= 1elif matrix[row][col] < target: row += 1else: return Truereturn False