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.
For example,
Consider the following matrix:
[[1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50]
GivenTarget=3, ReturnTrue.
If binary search is directly performed on matrix elements, the time complexity is O (M * n). In fact, it is easy to find the corresponding row by searching, then, find the existence of the domain name in the row, and use the simplest direct lookup method. The time complexity is only O (m + n). If the two searches use binary lookup, the time complexity can be reduced to O (logm + logn). The following is the O (m + n) code:
Class solution {public: bool searchmatrix (vector <int> & matrix, int target) {If (matrix. empty () return false; int M = matrix. size (); int n = matrix [0]. size (); int I = 0, j = 0; while (I <M & target> = matrix [I] [0]) I ++; I --; if (I =-1) return false; while (j <n) {If (target = matrix [I] [J]) return true; else J ++ ;} return false ;}};