力扣-74.搜索二维矩阵
题目链接
74.搜索二维矩阵
class Solution {public boolean searchMatrix(int[][] matrix, int target) {int m = matrix.length, n = matrix[0].length;int lowCol = 0, highCol = m - 1;while (lowCol <= highCol) {int midCol = (lowCol + highCol) / 2;if (matrix[midCol][0] < target) {lowCol = midCol + 1;} else if (matrix[midCol][0] > target) {highCol = midCol - 1;} else {return true;}}lowCol--;if (lowCol < 0)return false;int left = 0, right = n - 1;while (left <= right) {int mid = (left + right) / 2;if (matrix[lowCol][mid] < target) {left = mid + 1;} else if (matrix[lowCol][mid] > target) {right = mid - 1;} else {return true;}}return false;}
}
小结:依然是二分查找,注意边界值。