diff --git a/solutions/74. Search a 2D Matrix/README.md b/solutions/74. Search a 2D Matrix/README.md new file mode 100644 index 0000000..30f8edd --- /dev/null +++ b/solutions/74. Search a 2D Matrix/README.md @@ -0,0 +1,61 @@ +--- +comments: true +difficulty: medium +# Follow `Topics` tags +tags: + - Array + - Binary Search + - Matrix +--- + +# [74. Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/description/) + +## Description + +You are given a 2D integer matrix `matrix` of size `m x n` that satisfies the following conditions: + +Each row is sorted in non-decreasing order. + +The first number of each row is greater than the last number of the previous row. + +Given an integer `target`, determine whether it exists in the matrix. Return `true` if it is found, otherwise return `false`. + +Your solution must run in **O(log(m * n))** time. + + +**Example 1:** +``` +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 +Output: true +``` + +**Example 2:** +``` +Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 +Output: false +``` + +**Constraints:** + +* `m == matrix.length` +* `n == matrix[i].length` +* `1 <= m, n <= 100` +* `-10^4 <= matrix[i][j], target <= 10^4` + +## Solution + + +```java +``` + +```python +``` + +## Complexity + +- Time complexity: $$O(log(m * n))$$ + + +- Space complexity: $$O(1)$$ + + diff --git a/solutions/74. Search a 2D Matrix/Solution.java b/solutions/74. Search a 2D Matrix/Solution.java new file mode 100644 index 0000000..b2ce1d3 --- /dev/null +++ b/solutions/74. Search a 2D Matrix/Solution.java @@ -0,0 +1,21 @@ +class Solution { + public boolean searchMatrix(int[][] matrix, int target) { + int rows = matrix.length; + int cols = matrix[0].length; + int start = 0; + int end = rows * cols - 1; + while (start <= end) { + int mid = (start + end) / 2; + int row = mid / cols; + int col = mid % cols; + if (matrix[row][col] == target) { + return true; + } else if (matrix[row][col] < target) { + start = mid + 1; + } else { + end = mid - 1; + } + } + return false; + } +} diff --git a/solutions/74. Search a 2D Matrix/Solution.py b/solutions/74. Search a 2D Matrix/Solution.py new file mode 100644 index 0000000..c633fe3 --- /dev/null +++ b/solutions/74. Search a 2D Matrix/Solution.py @@ -0,0 +1,14 @@ +class Solution: + def searchMatrix(self, matrix: list[list[int]], target: int) -> bool: + rows, cols = len(matrix), len(matrix[0]) + start, end = 0, rows * cols - 1 + while start <= end: + mid = (start + end) // 2 + row, col = divmod(mid, cols) + if matrix[row][col] == target: + return True + elif matrix[row][col] < target: + start = mid + 1 + else: + end = mid - 1 + return False