LeetCode 0074 - Search a 2D Matrix
# Hints
- 二分查找
# 题面
Difficulty | Time Complexity Limit | Extra-Memory Complexity Limit |
---|---|---|
Medium |
Write an efficient algorithm that searches for a value in an 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
# 题意
给定一个 的矩阵,该矩阵的每行从左到右有序递增,且第 行的首元素比第 行的末元素大,要求实现在该矩阵中高效地查找某个值是否存在。
# 题解
由矩阵的有序性质不难想到用二分查找求解。
显然,假设目标值存在,那么在矩阵的第 列上查找大于等于 的第一行(事实上与 lower_bound
等价)即可确定对应的行号,再在该行上查找 是否存在即可,时间复杂度为 。
# AC代码
class Solution {
public:
bool searchMatrix(vector<vector<int>> & matrix, int target) {
// 特判
if (matrix.empty() || matrix.front().empty()) {
return false;
}
// 初始化
int m = matrix.size(), n = matrix.front().size();
// 二分查找行号
int rid = binary_search_1(matrix, m, n, target);
if (rid >= m) {
return false;
}
// 二分查找
bool res = binary_search_2(matrix, m, n, target, rid);
// 返回
return res;
}
// 二分查找行号
int binary_search_1(vector<vector<int>> & matrix, int m, int n, int target) {
int left = 0, right = m - 1;
int rid = left;
while (left <= right) {
int mid = (left + right) / 2;
if (target > matrix[mid][n - 1]) {
left = mid + 1;
rid = left;
} else {
right = mid - 1;
}
}
return rid;
}
// 二分查找
bool binary_search_2(vector<vector<int>> & matrix, int m, int n, int target, int rid) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (target == matrix[rid][mid]) {
return true;
}
if (target > matrix[rid][mid]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
};
- 01
- Reading Papers - Kernel Concurrency06-01
- 02
- Linux Kernel - Source Code Overview05-01
- 03
- Linux Kernel - Per-CPU Storage05-01