LC74. 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.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
代码
双指针法
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int tar) {
if (matrix.empty() || matrix[0].empty())
return false;
int n = matrix.size(), m = matrix[0].size();
cout << n << m << endl;
int i = 0, j = m - 1;
while (i < n && j >= 0) {
if (tar == matrix[i][j])
return true;
if (tar > matrix[i][j])
i++;
else
j--;
}
return false;
}
};
二分法
(二分) $O(logn)O(logn)$
我们可以想象把整个矩阵,按行展开成一个一维数组,那么这个一维数组单调递增,然后直接二分即可。
二分时可以通过整除和取模运算得到二维数组的坐标。
时间复杂度分析:二分的时间复杂度是 $O(logn^2)=O(logn)$。
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int tar) {
if(matrix.empty()||matrix[0].empty()) return false;
int n = matrix.size(), m = matrix[0].size();
int l = 0, r = m - 1, mid;
while(l < r) {
mid = (l + r) >> 1;
if(matrix[mid/m][mid%m] <= tar) r = mid;
else l = mid + 1;
}
return matrix[l/m][l%m] == tar;
}
};