Title:
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], [Ten, One,], [Max, +,]]
Given Target = 3 , return true .
Idea: According to test instructions, each line of the matrix is arranged sequentially and increments by line, so we can expand the MN matrix into a one-dimensional ordered array.
num represents the sequence number of the element, starting with 0. I, J represents the row and column coordinates in the matrix, starting with 0.
Num = N*i + j; = = i = num/n; j = Num% N; n represents the column of the Matrix. (drawing can be obtained)
Next, use the binary search to locate target.
Attention: Note the conversion of the sequence number and the matrix row number in the matrix.
int mid = lo + (Hi-lo)/2; int i = mid/n; Int j = mid% n;
Complexity: O (log (N))
AC Code: (My_code one_pass)
Class Solution {Public:bool Searchmatrix (vector<vector<int> > &matrix, int target) {//actually similar to MN The matrix is expanded into an array and then looked up, but the column//num is calculated based on the first element, and the sequence number representing the element, starting at 0. I,j represents the row and column coordinates in the matrix, starting with 0. Num = N*i + j; = = i = num/n; j = Num% n; n represents the column of the Matrix. BOOL ret = FALSE; if (matrix.size () = = 0 | | matrix[0].size () = = 0) return ret; int m = Matrix.size (); int n = matrix[0].size (); int lo = 0; int hi = (m-1) * n + (n-1); hi = m * n-1; while (lo <= hi) {int mid = lo + (Hi-lo)/2; int i = mid/n; Int j = mid% n; if (Target > Matrix[i][j]) {lo = mid + 1; } else if (Target < matrix[i][j]) {hi = mid-1; } else {ret = true; Break }} return ret; }};
[C + +] leetcode:61 Search a 2D Matrix