Write an efficient algorithm that searches for a value in an m x n matrix. 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.
new solution update 2022.02.13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution { public: boolsearchMatrix(vector<vector<int>>& matrix, int target){ int n = matrix.size(), l = 0, r = n - 1; while(l < r) { int m = l + (r-l)/2; if(matrix[m][0] == target) returntrue; elseif(matrix[m][0] > target) r = m - 1; elseif(matrix[m].back() < target) { l = m+1; } elseif(l == m) break; else l = m; } auto it = lower_bound(matrix[l].begin(), matrix[l].end(), target); return it != matrix[l].end() and *it == target; } };