Search a 2D matrix
Writean efficient algorithm that searches for a value inMXNMatrix. 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]
]
GivenTarget=3, Returntrue.
[Analysis-original]
/*** Creation Time: September 24, 2014 11:26:06 Project name: Test ** @ author Cao yanfeng * @ since JDK 1.6.0 _ 21 class description: check whether the sorted two-dimensional matrix has a two-layer binary search for a number, the first layer is to find the row */public class findmatrixtest {/*** @ Param ARGs */public static void main (string [] ARGs) {// todo auto-generated method stubint [] [] matrix = {1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 50 }}; system. out. println (searchmatrix (matrix, 13);} public static Boolean searchmatrix (INT [] [] matrix, int target) {int M = matrix. length; int n = matrix [0]. length; int I = 0, j = m-1; while (I <= J) {int middlerow = I + (J-I)> 1 ); if (target <matrix [middlerow] [0]) {J = middlerow-1; continue;} else if (target> matrix [middlerow] [n-1]) {I = middlerow + 1; continue;} else if (target> = matrix [middlerow] [0] & target <= matrix [middlerow] [n-1]) {return find (Matrix [middlerow], 0, n-1, Target) ;}} return false;} public static Boolean find (INT [] matrixrow, int start, int end, int target) {While (start <= END) {int middle = start + (end-Start)> 1); If (matrixrow [Middle] = target) {return true;} else if (matrixrow [Middle]> Target) {end = middle-1;} else if (matrixrow [Middle] <target) {start = middle + 1 ;}} return false ;}}
[Leetcode question record-13] Two-dimensional array after Binary Search sorting