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 from left to right.The first integer of each row is greater than the last integer of the previous row.For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]Given target = 3, return true.
Solution1:
public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0 || matrix[0].length == 0 || matrix[0][0] > target || matrix[matrix.length - 1][matrix[0].length - 1] < target) { return false; } int row = 0; while (matrix[row][matrix[0].length - 1] < target) { row++; } for (int i = 0; i < matrix[row].length; i++) { if (matrix[row][i] == target) { return true; } } return false; }Solution2:
better
public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0) return false; if (matrix[0].length == 0) return false; int rows = matrix.length; int cols = matrix[0].length; int begin = 0; int end = rows * cols - 1; while (begin != end) { int mid = (begin + end - 1) >> 1; if (matrix[mid / cols][mid % cols] < target) begin = mid + 1; else end = mid; } return matrix[end / cols][end % cols] == target; }