Search a 2D Matrix
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.
For example,
Consider the following matrix:
[ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 50] ]
Given target = 3
, return true
.
方法一:每行中,从左到右元素依次增大,每列中,从上到下元素依次增大,因此可以从右上角开始查找,若target小于matrix[i][j],那么--j,若target大于matrix[i][j],那么++i,继续比较target与matrix[i][j],直至找到或找不到
时间复杂度为O(m+n)
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int> > &matrix, int target) { 4 int rows = matrix.size(); 5 int cols = matrix[0].size(); 6 int i = 0, j = cols-1; 7 while( i<rows && j>=0 ) { 8 if( matrix[i][j] == target ) return true; 9 if( target < matrix[i][j] ) --j; //target小于matrix[i][j],那么往左边找 10 else ++i; //target大于matrix[i][j],那么往下面找 11 } 12 return false; 13 } 14 };
方法二:The first integer of each row is greater than the last integer of the previous row.
由于每行的第一个元素都比前面行的最后一个元素都大,因此可以考虑二分搜索
现在第一列二分搜索target,若找到,则直接返回true,找不到则返回target应该在的那一行,然后继续在那一行继续二分搜索target,时间复杂度为O(logm+logn)
1 class Solution { 2 public: 3 bool searchMatrix(vector<vector<int> > &matrix, int target) { 4 int rows = matrix.size(); 5 int cols = matrix[0].size(); 6 int low = 0, high = rows-1; 7 while( low <= high ) { //在第一列进行二分搜索 8 int mid = low + (high - low)/2; 9 if( matrix[mid][0] == target ) return true; 10 if( target < matrix[mid][0] ) high = mid-1; 11 else { 12 if( target > matrix[mid][cols-1] ) //若大于第一个元素及最后一个元素 13 low = mid+1; 14 else { //若小于最后一个元素,那么target理论上应该在mid所在的行中 15 low = mid; 16 break; 17 } 18 } 19 } 20 if( low >= rows ) return false; 21 int row = low; 22 low = 0, high = cols-1; 23 while( low <= high ) { //在搜到的行进行二分搜索 24 int mid = low + (high-low)/2; 25 if( target == matrix[row][mid] ) return true; 26 if( target > matrix[row][mid] ) low = mid+1; 27 else high = mid-1; 28 } 29 return false; 30 } 31 };