First, we use binary search in the last column to find which row the target supposed to be in. Initially, we set rowLow = 0, rowHigh = row-1. The condition of the while loop is rowLow < rowHigh. we get the middle postion of rowLow and rowHigh, which is rowMid = (rowLow+rowHigh)/2, here we do not need to concern about the overrange of integer value. we compare the value in the middle position, if equal to target, return true; if larger than target, set high = mid-1; if smaller than target, set low = mid+1; Finally when the loop ends, the rowLow equals to rowHigh, and we only leave the row-rowLow unchecked. Then we compare the value of matrix[rowLow][col-1] with target, if same return true, if smaller than target, then the target should be in the row ++rowLow, but if rowLow == row, that means target is larger than biggest value in the matrix, return false. Then we examine the row rowLow. Once again we use binary search to find whether target is in the row.
Code:
public class Solution { public boolean searchMatrix(int[][] matrix, int target) { int row = matrix.length; int col = matrix[0].length; if(row == 0 || col == 0) return false; int rowLow = 0, rowHigh = row-1; int colLow = 0, colHigh = col-1; while(rowLow < rowHigh){ int rowMid = (rowLow + rowHigh)/2; if(target == matrix[rowMid][col-1]) return true; else if(target < matrix[rowMid][col-1]) rowHigh = rowMid - 1; else rowLow = rowMid + 1; } if(matrix[rowLow][col-1] == target) return true; if(matrix[rowLow][col-1] < target) rowLow++; if(rowLow == row) return false; while(colLow < colHigh){ int colMid = (colLow+colHigh)/2; if(target == matrix[rowLow][colMid]) return true; else if(target < matrix[rowLow][colMid]) colHigh = colMid - 1; else colLow = colMid + 1; } if(matrix[rowLow][colLow] == target) return true; else return false; } }