LeetCode - 74. 搜索二维矩阵

74. 搜索二维矩阵

编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

  • 每行中的整数从左到右按升序排列。
  • 每行的第一个整数大于前一行的最后一个整数。
    LeetCode - 74. 搜索二维矩阵_第1张图片
    解题思路: 本题本质上还是在考察二分查找,二维数组本质上依然是一维数组,因此转换成熟知的一维数组的二分查找即可解题。请看代码。
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if (matrix.empty() || matrix[0].empty()) return false;
        int rows = matrix.size(), cols = matrix[0].size();
        int left = 0, right = rows * cols - 1;
        while (left < right) {
            int mid = (left + right) / 2;
            if (matrix[mid / cols][mid % cols] < target) left = mid + 1;
            else right = mid;
        }
        return matrix[right / cols][right % cols] == target;
    }
};

你可能感兴趣的:(LeetCode,二分法)