Search a 2D matrix
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]]
Given target =3, Returntrue.
Idea: perform a vertical binary search to determine the row where the target is located, and then perform a common binary search.
Class solution {public: bool searchmatrix (vector <int> & matrix, int target) {If (matrix. empty () return false; else if (Matrix [0]. empty () return false; else {int M = matrix. size (); int n = matrix M-1]. size (); // determine if (Matrix [0] [0]> Target | matrix M-1] [n-1] <target) return false; // locate the row int low = 0 based on the first binary search; int high = m-1; int mid; int num; while (low <= high) {mid = (low + high)/2; num = matrix [Mid] [0]; If (num = target) return true; else if (Num> target) high = mid-1; else low = Mid + 1;} // short-circuit operation to prevent cross-border if (low> = M | matrix [low] [0]> target) low-= 1; int ROW = low; // perform binary search in the row where the row is located. Low = 0; high = matrix [row]. size ()-1; while (low <= high) {mid = (low + high)/2; num = matrix [row] [Mid]; if (num = target) return true; else if (Num> Target) High = mid-1; else low = Mid + 1;} return false ;}}};
[Leetcode] search a 2D matrix