74. 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

AC代码

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty() || matrix[0].empty()) return false;
        int m = matrix.size();
        int up = 0, down = m - 1, mid = 0;
        while (up <= down) {
            mid = (up + down) / 2;
            if (matrix[mid][0] > target) down = mid - 1;
            else if (matrix[mid][0] < target) up = mid + 1;
            else return true;
        }
        if (mid != 0 && matrix[mid][0] > target) mid -= 1; //注意这一行
        auto it = lower_bound(matrix[mid].begin(), matrix[mid].end(), target);
        if (it == matrix[mid].end() || *it != target) return false;
        return true;
    }
};

总结

使用了两次二分,一开始没写注释的那一行,最后几个点炸了,然后这一行是我蒙上去的,结果AC了,我也解释不出来为什么要添加这一行,而且不写这一行居然能过那么多的测试

猜你喜欢

转载自blog.csdn.net/weixin_34115824/article/details/91028554