Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions solutions/74. Search a 2D Matrix/README.md
Original file line number Diff line number Diff line change
@@ -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))$$
<!-- Add time complexity here, e.g. $$O(n)$$ -->

- Space complexity: $$O(1)$$
<!-- Add space complexity here, e.g. $$O(n)$$ -->

21 changes: 21 additions & 0 deletions solutions/74. Search a 2D Matrix/Solution.java
Original file line number Diff line number Diff line change
@@ -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;
}
}
14 changes: 14 additions & 0 deletions solutions/74. Search a 2D Matrix/Solution.py
Original file line number Diff line number Diff line change
@@ -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