Title Link: Search-a-2d-matrix
/** * Write An efficient algorithm the searches for a value in a m x n matrix. The This matrix have the following properties:integers in each row is sorted from left to right. The first integer of each row was greater than the last integer of the previous row. For Example,consider the following matrix:[[1, 3, 5, 7], [Ten, One,,], [Max, +, 50]]given target = 3, Retu RN true. * */public class Searcha2dmatrix {//134/134 test cases passed.//status:accepted//runtime:236 ms//submitted:0 minutes ago//time complexity O (log (max (m,n)) space complexity O (1) Static Boolean Searchmatrix (int[][] matrix, int target) {int m = m Atrix.length; Number of rows int n = matrix[0].length;//number of columns int up = 0; int down = m-1; int left = 0; int right = n; Dichotomy find the row while (up < down) {int mid = (down + up)/2; if (matrix[mid][n-1] > target) down = mid; else if (Matrix[mid][n-1] < target) up = mid + 1; else return TruE }//Two-way to find the column while (left < right) {int mid = (left + right)/2; if (Matrix[up][mid] > target) right = mid; else if (Matrix[up][mid] < target) left = mid + 1; else return true; } return false; }public static void Main (string[] args) {System.out.println (Searchmatrix (New Int[][]{{1, 3, 5, 7},{10, 11, 16, 20},{23, 30, 34, 50}}, 3)); System.out.println (Searchmatrix (New Int[][]{{1, 1}, 2)); System.out.println (Searchmatrix (New Int[][]{{1,}, {3}}, 2)); System.out.println (Searchmatrix (New Int[][]{{1}, 1));}}
[Leetcode 74] Search a 2D Matrix