Write an efficient algorithm, searches for a value in a m x n Matrix. This matrix has the following properties:
- Integers in each row is sorted in ascending from left to right.
- Integers in each column is sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[ [1, 4, 7, one, a], [2, 5, 8,, + ], [3, 6, 9, +, +], [10, 13, 14, 17, [18, 21, 23, 26, 30]
Given target = 5
, return true
.
Given target = 20
, return false
.
1 Public classSolution {2 Public BooleanSearchmatrix (int[] Matrix,inttarget) {3 if(Matrix.length = = 0 | | matrix[0].length = = 0)return false;4 inti = 0,j = Matrix[0].length-1;5 while(I < matrix.length && J >= 0){6 if(Matrix[i][j] = = target)return true;7 if(Matrix[i][j] < target) i++;8 Elsej--;9 }Ten return false; One } A}
The matrix is special and can be compared from the top right x, if target > x, then to the next line, if Target < X, then go back one column. The topic has appeared in the beauty of programming.
Solution 2: The problem can also be found using the dichotomy method.
Search a 2D Matrix II Java Solutions