LeetCode.74 - Search a 2D Matrix

  一开始 [[]] 没过,我还以为是编译器错误 (/捂脸

class Solution {
public:
    bool searchMatrix(vector<vector<int>> matrix, int target) {
        int min = -1, max = matrix.size();
        if (max == 1 && matrix[0].empty()) return false; // 注意 [[]] 这种情况
        while (min + 1 != max)
        {
            int mid = (min + max) / 2;
            if (matrix[mid][0] <= target && matrix[mid][matrix[0].size() - 1] >= target)
            {
                if (matrix[mid][0] == target || matrix[mid][matrix[0].size() - 1] == target)
                    return true;
                min = -1, max = matrix[0].size();
                while (min + 1 != max)
                {
                    int mid_cols = (min + max) / 2;
                    if (matrix[mid][mid_cols] == target) return true;
                    else if (matrix[mid][mid_cols] > target) max = mid_cols;
                    else min = mid_cols;
                }
                return false;
            }
            else if (target < matrix[mid][0])
                max = mid;
            else if (target > matrix[mid][matrix[0].size() - 1])
                min = mid;
        }
        return false;
    }
};

  

上一篇:discuz 格子广告排版问题


下一篇:【LeetCode】221. 最大正方形(DP)