参考思路
⏰ 时间复杂度: O ( n log n ) O(n\log{n}) O(nlogn)
空间复杂度: O ( 1 ) O(1) O(1)
class Solution {
public boolean searchMatrix(int[][] matrix, int target)
{
int n = matrix.length;
int m = matrix[0].length;
if (n == 0 || m == 0)
return false;
for (int i = 0; i < n; i++)
{
if (matrix[i][0] > target)
break;
if (matrix[i][m - 1] < target)
continue;
int col = bsearch(matrix[i], target);
if (matrix[i][col] == target)
return true;
}
return false;
}
// 在 a 中二分查找 x,没找到返回 -1
private int bsearch(int[] a, int x)
{
int l = 0;
int r = a.length - 1;
while (l < r)
{
int m = l + r >> 1;
if (a[m] >= x)
r = m;
else
l = m + 1;
}
return l;
}
}
参考题解
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int m = matrix.length, n = matrix[0].length;
int r = 0,c = n-1;
while (r < m && c >= 0)
{
if(matrix[r][c] < target) //目标值较大,走右子树
r++;
else if(matrix[r][c] > target)//目标值较小,走左子树
c--;
else
return true;
}
return false;
}
}