Title Description: (link)
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 .
Problem Solving Ideas:
Two-point Search
1 classSolution {2 Public:3 BOOLSearchmatrix (vector<vector<int>>& Matrix,inttarget) {4 intFirst =0;5 intLast = Matrix.size ()-1;6 intLen = matrix[0].size ();7 while(First <=Last ) {8 intMID = first + (Last-first)/2;9 if(matrix[mid][0] <= target && target <= Matrix[mid][len-1] ) {Ten returnBinarySearch (Matrix[mid], target); One}Else if(matrix[mid][0] >target) { ALast = mid-1; -}Else if(Matrix[mid][len-1] <target) { -First = mid +1; the } - } - - return false; + } - + Private: A BOOLBinarySearch (vector<int>& VEC,inttarget) { at intFirst =0; - intLast = Vec.size ()-1; - while(First <=Last ) { - intMid= first + (Last-first)/2; - if(Vec[mid] = =target) { - return true; in}Else if(Vec[mid] <target) { -First = mid +1; to}Else { +Last = mid-1; - } the } * $ return false;Panax Notoginseng } -};
[Leetcode] Search a 2D Matrix