[力扣] 算法 74 (C++)

74. 搜索二维矩阵

class Solution {
public:
    bool searchMatrix(vector<vector<int>>&amp; matrix, int target) {
        int row = matrix.size();
        int col = matrix[0].size();
        int left = 0, right = row * col - 1;
        while (left < right) {
            auto mid = (left + right) / 2;
            auto num = matrix[mid / col][mid % col];
            if (num == target) 
                return true;
            if (num < target)
                left = mid + 1;
            else
                right = mid - 1;
        }
        return matrix[left / col][left % col] == target;
    }
};

发表评论