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 from the left to the 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., +]]
Given target = 3
, return true
.
Analysis:
Write an efficient algorithm to search for values in the m x n Matrix. This matrix has the following characteristics:
- The integers in each row are sorted from left to right.
- The first number of each row is greater than the last integer on the previous line.
This problem can be a two-dimensional array of numbers as an ordered list, the two-way search.
Public classSolution { Public BooleanSearchmatrix (int[] Matrix,inttarget) { if(Matrix = =NULL|| Matrix.length = = 0) { return false; } if(Matrix[0] = =NULL|| Matrix[0].length = = 0) { return false; } introw = matrix.length, column = Matrix[0].length; intStart = 0, end = row * Column-1; while(Start + 1 <end) { intMID = start + (End-start)/2; intNumber = Matrix[mid/column][mid%column]; if(Number = =target) { return true; } Else if(Number <target) {Start=mid; } Else{End=mid; } } if(matrix[start/column][start% column] = =target) { return true; } Else if(matrix[end/column][end% column] = =target) { return true; } return false; }}
Leetcode 74. Search a 2D Matrix