240 Search a 2D Matrix II

1. Question

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
1
[
2
[1, 4, 7, 11, 15],
3
[2, 5, 8, 12, 19],
4
[3, 6, 9, 16, 22],
5
[10, 13, 14, 17, 24],
6
[18, 21, 23, 26, 30]
7
]
Copied!
Given target=5, returntrue.
Given target=20, returnfalse.

2. Implementation

(1) Binary Search
1
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
7
int m = matrix.length, n = matrix[0].length;
8
9
int rowStart = 0, rowEnd = m - 1, rowMid = 0;
10
11
while (rowStart + 1 < rowEnd) {
12
rowMid = rowStart + (rowEnd - rowStart) / 2;
13
14
if (matrix[rowMid][0] < target) {
15
rowStart = rowMid + 1;
16
}
17
else {
18
rowEnd = rowMid;
19
}
20
}
21
22
rowStart = matrix[rowStart][0] >= target ? rowStart : rowEnd;
23
24
for (int i = 0; i <= rowStart; i++) {
25
int colStart = 0, colEnd = n - 1, colMid = 0;
26
27
while (colStart <= colEnd) {
28
colMid = colStart + (colEnd - colStart) / 2;
29
30
if (matrix[i][colMid] == target) {
31
return true;
32
}
33
else if (matrix[i][colMid] < target) {
34
colStart = colMid + 1;
35
}
36
else {
37
colEnd = colMid - 1;
38
}
39
}
40
}
41
return false;
42
}
43
}
Copied!

3. Time & Space Complexity

Binary Search: 时间复杂度O(logm + mlogn), 空间复杂度O(1)