Poison

74. Search a 2D Matrix

Compare
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int i = m - 1, j = 0;
while (i >= 0 && j < n) {
if (matrix[i][j] > target) {
i--;
} else if (matrix[i][j] < target) {
j++;
} else {
return true;
}
}

return false;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int i = 0, j = m * n - 1;
while (i <= j) {
int mid = (i + j) >> 1;
int value = matrix[mid / n][mid % n]; // 注意定位行的索引时是除以 n
if (value > target) {
j = mid - 1;
} else if (value < target) {
i = mid + 1;
} else {
return true;
}
}

return false;
}
}
Reference

74. Search a 2D Matrix