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,], [23, 30, 34, 50]]
Given target = 3
, return true
.
The topic is to give a matrix, according to a small arrival, and then given a number, determine whether the number in the matrix.
Is the application of the dichotomy method. Two methods, the first kind is slightly slower.
The first is to use the two-way, first find the number of trips, and then in this line to find the specific existence.
The second is the direct application of the dichotomy, more efficient.
Public classSolution { Public BooleanSearchmatrix (int[] Matrix,inttarget) { intLen1 =matrix.length; if(Len1 = = 0 ) return false; intLen2 = matrix[0].length; if(Len2 = = 0 | | Target < MATRIX[0][0]) return false; intRow_start = 0,row_end = Len1-1; intCol_start = 0,col_end = len2-1; introw = (Row_end+row_start)/2, col; while(Row_start <=row_end) {Row= (Row_end+row_start)/2; if(Target >= matrix[row][0] ){ if(row = = Len1-1 | | Target < MATRIX[ROW+1][0]) Break; ElseRow_start= Row+1; } Else{ if(row = = 0 | | target >= matrix[row-1][0]) {row--; Break; } ElseRow_end= Row-1; } } while(Col_start <=col_end) {Col= (Col_end+col_start)/2; if(Target >Matrix[row][col]) { if(col = =col_end)return false; ElseCol_start= Col+1; }Else if(Target <Matrix[row][col]) { if(col = =Col_start)return false; ElseCol_end= Col-1; }Else return true; } return false; }}
Public classSolution { Public BooleanSearchmatrix (int[] Matrix,inttarget) { intLen1 =matrix.length; if(Len1 = = 0 ) return false; intLen2 = matrix[0].length; if(Len2 = = 0 | | Target < MATRIX[0][0]) return false; intStart = 0,end = len1*len2-1, Flag; while(Start <=end) {Flag= (start+end)/2; intnum = matrix[flag/len2][flag%Len2]; if(Target >num) Start= Flag+1; Else if(Target <num) End= Flag-1; Else return true; } return false; }}
Leetcode Search a 2D Matrix-----java