240. Search a 2D Matrix II
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 in ascending from left to right.
- Integers in each column are sorted in ascending from top to bottom.
For example,
Consider the following matrix:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
Given target = 5, return true.
Given target = 20, return false.
分析:
首先看到题目的设定,是行和列分别降序,那么最自然的想法就是,我先在行找,如果找到一个值,它的前一个值比pivot小,后一个值比pivot大,那么再从这一列往下找,如果找到了比该值大的值还没找到,则断定没有这个值。
但是这样的做法是时间复杂度是O(n+m),因此,对于这种有序数组中查找数的题目,我们很自然可以想到用二分法查找,用二分法代替上面的逐个查找,那么复杂的就能降到O(mlogn)。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool searchMatrix(vector<vector<int>>& matrix, int target) {
if (matrix.empty() || matrix.size() < 1 || matrix[0].size() < 1) {
return false;
}
return searchRecCol(matrix, target, 0, matrix.size() - 1);
}
bool searchRecCol(vector<vector<int>>& matrix, int target, int top, int bottom) {
if (top > bottom)
return false;
int mid = top + (bottom - top) / 2;
if (matrix[mid].front() <= target && target <= matrix[mid].back())
if (searchRow(matrix[mid], target))
return true;
if (searchRecCol(matrix, target, top, mid - 1)) return true;
if (searchRecCol(matrix, target, mid + 1, bottom)) return true;
return false;
}
bool searchRow(vector<int>& vector, int target) {
int left = 0, right = vector.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (vector[mid] == target)
return true;
if (vector[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return false;
}
};