Title Description:
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.
Code implementation:
Public classSolution {/** @param Matrix:matrix, a list of lists of integers * @param target:an integer * @return: A Boolean, in Dicate whether matrix contains target*/ 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; intCol = matrix[0].length; intStart = 0; intend = row * COL-1; while(Start <=end) {System.out.println (start); intMid = (end + start)/2; intnum = matrix[mid/col][mid%Col]; if(num==target) { return true; }Else if(Num >target) {End= Mid-1; }Else{Start= Mid+1; } } return false; }}
Remark: A problem that pits me,
1. Two-point lookup, where mid has two representations, one (End+start)/2, one start+ (End-start)/2
2. Know the index to seek the elements of the matrix: using index/col column elements;
lintcode-search two-dimensional matrix Java