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],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
1 classSolution {2 Public:3 BOOLSearchmatrix (vector<vector<int> >& Matrix,inttarget) {4 intcol=matrix[0].size ();5 introw=matrix.size ();6 7 inttargetrow=0;8 intflag=0;9 Ten One if(0==col-1&&0==row-1) A { - if(target==matrix[0][0]) - return true; the Else - return false; - } - + - for(intI=0; i<row;i++) + { A if(target<matrix[0][0]) at { - return false; - } - if(target==matrix[i][0]) - { - return true; in } - if(target<matrix[i][0]&&i>=1) to { +flag=1; -targetrow=i-1; the Break; * } $ if(target<matrix[row-1][col-1])Panax Notoginseng { -flag=1; thetargetrow=row-1; + } A if(target==matrix[row-1][col-1]) the { + return true; - } $flag=0; $ } - - the for(intI=0; i<col;i++) - {Wuyi if(target==Matrix[targetrow][i]) the { -flag=1; Wu Break; - } Aboutflag=0; $ } - - if(0==flag) - return false; A Else + return true; the } -};
"Leetcode" Search 2D Matrix