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:
[[1, 3, 5, 7], [Ten, one, +,], [Max., +]]
Given Target = 3
, return true
.
algorithm:find the first column two points first, and then find the second part of the rowAccepted Code:
Class Solution {Public:bool Searchmatrix (vector<vector<int>>& matrix, int target) {int M=matri X.size (); int n=matrix[0].size (); int top=0; int bottom=m-1; int mid1=0; if (Matrix[0][0]==target) return true; while (Top<=bottom) {mid1=top+ (bottom-top)/2; if (Matrix[mid1][0]==target) return true; else if (matrix[mid1][0]<target) top=mid1+1; else bottom=mid1-1; } if (Matrix[mid1][0]>target) {if (mid1>0) mid1--; else return false; } int left=0; int right=n-1; while (left<=right) {int mid2=left+ (right-left)/2; if (Matrix[mid1][mid2]==target) return true; else if (matrix[mid1][mid2]<target) left=mid2+1; else right=mid2-1; } return false; }};
Leetcode No74. Search a 2D Matrix