20. Looking for a 2D matrix
Given a m*n matrix that increments from left to right from top to bottom, determine if Target is in the matrix
Cases:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Target=3
Return: True
Idea: two-point search
Code:
public class Test {public static Boolean Searchmatrix (int[][] matrix, int target) {if (Matrix = = NULL | | matrix.length = = 0 | | Matrix[0].length = = 0) return false;int m = matrix.length;int n = matrix[0].length;int begin = 0;int end = m * N-1;while (Begin < End) {int mid = (begin + End)/2;int Midx = mid/n;int Midy = mid% n;if (Matrix[midx][midy] = = target) return true;if (matrix [Midx] [Midy] < target) {begin = mid + 1;} else {end = mid-1;}} return false;} public static void Main (string[] args) {int[][] arr = {{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50}}; System.out.println (Searchmatrix (arr, 3));}}
Interview 10 Big algorithm Rollup-strings and Arrays 9