Skip to content

Commit 1d4fc03

Browse files
committed
add solution of problem 74: search a 2D matrix
1 parent 73a2eb5 commit 1d4fc03

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

SearchA2DMatrix74/README.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Write an efficient algorithm that searches for a value in an *m* x *n* matrix. This matrix has the following properties:
2+
3+
- Integers in each row are sorted from left to right.
4+
- The first integer of each row is greater than the last integer of the previous row.
5+
For example,
6+
7+
Consider the following matrix:
8+
```
9+
[
10+
[1, 3, 5, 7],
11+
[10, 11, 16, 20],
12+
[23, 30, 34, 50]
13+
]
14+
```
15+
Given **target** = `3`, return `true`.

SearchA2DMatrix74/Solution.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
public class Solution {
2+
public boolean searchMatrix(int[][] matrix, int target) {
3+
if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
4+
return false;
5+
6+
int rowIdx = 0;
7+
int colsNum = matrix[0].length;
8+
int rowsNum = matrix.length;
9+
10+
while (rowIdx < rowsNum && matrix[rowIdx][colsNum - 1] < target)
11+
rowIdx++;
12+
13+
if (rowIdx == rowsNum)
14+
return false;
15+
16+
int left = 0;
17+
int right = colsNum - 1;
18+
19+
while (left <= right) {
20+
int mid = (left + right) >> 1;
21+
if (matrix[rowIdx][mid] < target)
22+
left = mid + 1;
23+
else if (matrix[rowIdx][mid] > target)
24+
right = mid - 1;
25+
else
26+
return true;
27+
}
28+
29+
return false;
30+
}
31+
}

0 commit comments

Comments
 (0)