74. Search a 2D Matrix
刷
June-21-2019
这个居然也没记过?
二维转一维,用的究极二分大法,但是如果因为超左右边界而找不到。
[[2,3,5,7],[10,11,16,20],[23,30,34,50]]
51
yes left, no right => 找不到的话L是停在最右边超过的地方,最后判断会out of boundary..
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return false;
int row = matrix.length;
int col = matrix[0].length;
if (target < matrix[0][0] || target > matrix[row - 1][col - 1]) return false;
int l = 0, r = row * col - 1;
while (l <= r) {
int m = l + (r - l) / 2;
int val = matrix[m / col][m % col];
if (val == target) {
r = m - 1;
} else if (val < target) {
l = m + 1;
} else {
r = m - 1;
}
}
return matrix[l / col][l % col] == target;
}