"074-search a 2D matrix (search for two-dimensional matrices)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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:given target = 3, return true.
[ [1, 3, 5, 7], [10111620], [23303450]]
Main Topic
Given a two-dimensional matrix, an algorithm is implemented to achieve a fast search in the matrix. That is, given K, search for K in the matrix.
The following properties are in the matrix: Each row is ordered, and the first number of each row is greater than the last number on the previous line.
Thinking of solving problems
Solution One: First with the binary view algorithm to find the number of the column, and then use the binary search algorithm to find the column of the number. Returns true if found, otherwise false is returned. Solution two: See "sword refers to offer study" "Face question 3: Find in a two-dimensional array"
Code Implementation
Algorithm implementation class
Public classSolution { PublicBooleanSearchmatrix(int[] Matrix,intTarget) {if(Matrix = =NULL|| Matrix.length = =0|| matrix[0].length = =0) {return false; }introw = Matrix.length;intColumn = matrix[0].length;intLow =0;intHigh = row-1;intMID =0;//Find the column where the result resides while(Low <= High) {mid = low + (high-low)/2;if(Target < Matrix[mid][column-1]) {high = mid-1; }Else if(Target > Matrix[mid][column-1]) {low = Mid +1; }Else{return true; } }//Determine the final position of the column intTargetrow = mid;if(Matrix[mid][column-1] < target) {targetrow++; }//target column exceeded, no result if(Targetrow >= Row) {return false; } low =0; High = column-1;//Find the row that is located, find return True, no return false while(Low <= High) {mid = low + (high-low)/2;if(Target < Matrix[targetrow][mid]) {High = mid-1; }Else if(Target > Matrix[targetrow][mid]) {Low = mid +1; }Else{return true; } }return false; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47142931"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"leetcode-Interview algorithm classic-java Implementation" "074-search a 2D matrix (search two-dimensional matrix)"