Write an efficient algorithm that searches for a value inMXNMatrix. This matrix has the following properties:
- Integers in each row are sorted from left to right.
- The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input: matrix = [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] target = 3 output: true
Example 2:
Input: matrix = [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] target = 13 output: false
My code:
Class solution {public: bool searchmatrix (vector <int> & matrix, int target) {int ROW = matrix. size (); If (ROW = 0) return false; int Col = matrix [0]. size (); If (COL = 0) return false; int flag = 0; For (INT I = 0; I <row; ++ I) {If (Matrix [I] [col-1]> = target) {flag = I; break;} int L = 0, r = Col; while (L <R) {int M = (L + r)/2; If (Matrix [flag] [m] = target) return true; If (Matrix [flag] [m]> target) {r = m;} If (Matrix [flag] [m] <target) {L = m + 1 ;}} return false ;}};
Runtime:Eight MS, faster97.84% of C ++ online submissions for search a 2D matrix.
74. Search a 2D matrix