class Solution { // 两种二分模版 public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length == 0 || matrix[0].length == 0) return false; int m = matrix.length, n = matrix[0].length; int l = 0, r = m * n - 1; while(l <= r) { // 判断区间内所有点 int mid = (l + r) >> 1; if(matrix[mid/n][mid%n] == target) return true; else if (matrix[mid/n][mid%n] < target) { l = mid + 1; } else { r = mid - 1; } } return false; } public boolean searchMatrix(int[][] matrix, int target) { if(matrix.length == 0 || matrix[0].length == 0) return false; int m = matrix.length, n = matrix[0].length; int l = 0, r = m * n - 1; while(l < r) { // 注意二分的两种终止条件l < r 没有判断完成区间内所有点l == r情况 int mid = (l + r) >> 1; if(matrix[mid/n][mid%n] == target) return true; else if (matrix[mid/n][mid%n] < target) { l = mid + 1; // l 小的话一直向右逼近 } else { r = mid; // mid-1和mid都可以 } } // 退出循环继续判断 return matrix[l/n][l%n] == target; } }