Title Link: Search a 2D Matrix
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],
Given Target = 3, return true.
The requirement for this problem is to find the specified element target in the m*n matrix. And each row in the matrix is ordered, and the first element of each row is greater than the last element of its previous row.
The idea is a sentence: The two-dimensional array as an ordered array, the direct two-point search.
Time complexity: O (log (m+n))
Space complexity: O (1)
1 class Solution2 {3 Public:4 BOOL Searchmatrix(Vector<Vector<int> > &Matrix, int Target)5 {6 int m = Matrix.size(), N = Matrix[0].size();7 8 int L = 0, R = m * N - 1;9 while(L <= R)Ten { One int Mid = (L + R) / 2; A if(Matrix[Mid / N][Mid % N] == Target) - return true; - Else if(Matrix[Mid / N][Mid % N] > Target) the R = Mid - 1; - Else - L = Mid + 1; - } + - return false; + } A };
Reprint please indicate source: Leetcode---74. Search a 2D Matrix
Leetcode---74. Search a 2D Matrix