Skip to content

Commit cdfe482

Browse files
authored
Merge pull request #17 from xchux/feature/74-search-a-2d-matrix
✨ (Solution): Problem 74. Search a 2D Matrix
2 parents f7bb93d + 1fca743 commit cdfe482

File tree

3 files changed

+96
-0
lines changed

3 files changed

+96
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
---
2+
comments: true
3+
difficulty: medium
4+
# Follow `Topics` tags
5+
tags:
6+
- Array
7+
- Binary Search
8+
- Matrix
9+
---
10+
11+
# [74. Search a 2D Matrix](https://leetcode.com/problems/search-a-2d-matrix/description/)
12+
13+
## Description
14+
15+
You are given a 2D integer matrix `matrix` of size `m x n` that satisfies the following conditions:
16+
17+
Each row is sorted in non-decreasing order.
18+
19+
The first number of each row is greater than the last number of the previous row.
20+
21+
Given an integer `target`, determine whether it exists in the matrix. Return `true` if it is found, otherwise return `false`.
22+
23+
Your solution must run in **O(log(m * n))** time.
24+
25+
26+
**Example 1:**
27+
```
28+
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
29+
Output: true
30+
```
31+
32+
**Example 2:**
33+
```
34+
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
35+
Output: false
36+
```
37+
38+
**Constraints:**
39+
40+
* `m == matrix.length`
41+
* `n == matrix[i].length`
42+
* `1 <= m, n <= 100`
43+
* `-10^4 <= matrix[i][j], target <= 10^4`
44+
45+
## Solution
46+
47+
48+
```java
49+
```
50+
51+
```python
52+
```
53+
54+
## Complexity
55+
56+
- Time complexity: $$O(log(m * n))$$
57+
<!-- Add time complexity here, e.g. $$O(n)$$ -->
58+
59+
- Space complexity: $$O(1)$$
60+
<!-- Add space complexity here, e.g. $$O(n)$$ -->
61+
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public boolean searchMatrix(int[][] matrix, int target) {
3+
int rows = matrix.length;
4+
int cols = matrix[0].length;
5+
int start = 0;
6+
int end = rows * cols - 1;
7+
while (start <= end) {
8+
int mid = (start + end) / 2;
9+
int row = mid / cols;
10+
int col = mid % cols;
11+
if (matrix[row][col] == target) {
12+
return true;
13+
} else if (matrix[row][col] < target) {
14+
start = mid + 1;
15+
} else {
16+
end = mid - 1;
17+
}
18+
}
19+
return false;
20+
}
21+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
class Solution:
2+
def searchMatrix(self, matrix: list[list[int]], target: int) -> bool:
3+
rows, cols = len(matrix), len(matrix[0])
4+
start, end = 0, rows * cols - 1
5+
while start <= end:
6+
mid = (start + end) // 2
7+
row, col = divmod(mid, cols)
8+
if matrix[row][col] == target:
9+
return True
10+
elif matrix[row][col] < target:
11+
start = mid + 1
12+
else:
13+
end = mid - 1
14+
return False

0 commit comments

Comments
 (0)