publicclassSearcha2DMatrixII{ /** * Write an efficient algorithm that searches for a value in an m x n matrix. * This matrix has the following properties: * * Integers in each row are sorted in ascending from left to right. * Integers in each column are sorted in ascending from top to bottom. * Example: * * Consider the following matrix: * * [ * [1, 4, 7, 11, 15], * [2, 5, 8, 12, 19], * [3, 6, 9, 16, 22], * [10, 13, 14, 17, 24], * [18, 21, 23, 26, 30] * ] * [ * [3, 5, 9, 9, 14], * [7, 8, 11, 15, 15], * [8,10, 16, 16, 17]] * 12 * Given target = 5, return true. * * Given target = 20, return false. */ publicbooleansearchMatrix(int[][] matrix, int target){ int lx = 0; int ly = 0; int rx = matrix[0].length-1; int ry = matrix.length-1; while (lx < rx && ly < ry) { int midx = (lx + rx) / 2; int midy = (ly + ry) / 2; if ( matrix[midx][midy] == target) returntrue; elseif (matrix[midx][midy] < target) { lx = midx + 1; ly = midy + 1; } else { rx = midx; ry = midy; } }
int l = 0; int r = lx; while (l <= r) { int mid = (l + r) / 2; if (matrix[ly][mid] == target) returntrue; elseif (matrix[ly][mid] < target) l = mid + 1; else r = mid - 1; }
l = 0; r = ly; while (l <= r) { int mid = (l + r) /2; if (matrix[mid][lx] == target) returntrue; if (matrix[mid][lx] < target) l = mid + 1; else r = mid - 1; }