面试经典 150 题 2 —(二分查找)— 74. 搜索二维矩阵

74. 搜索二维矩阵

面试经典 150 题 2 —(二分查找)— 74. 搜索二维矩阵_第1张图片

方法
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int matrixRows = matrix.size(), matrixCols = matrix[0].size();
        // 先找target所在的行
        int targetAtRow = -1;
        for(int i = 0; i < matrixRows; i++){
            if(matrix[i][0] <= target && target <= matrix[i][matrixCols - 1]){
                targetAtRow = i;
                break;
            }
        }
        // 说明矩阵中没有target
        if(targetAtRow == -1){
            return false;
        }
        // 在target所在的行中用二分查找
        int left = 0, right = matrixCols - 1;
        while(left <= right){
            int middle = (right - left) / 2 + left;
            if(matrix[targetAtRow][middle] == target){
                return true;
            }
            else if(matrix[targetAtRow][middle] < target){
                left = middle + 1;
            }
            else{
                right = middle - 1;
            }
        }
        return false;
    }
};
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int matrixRows = matrix.size(), matrixCols = matrix[0].size();
        // 先找target所在的行
        int high = 0, low = matrixRows - 1;
        while(high <= low){
            int middle = (low - high) / 2 + high;
            if(matrix[middle][0] <= target){
                high = middle + 1; // 循环中是<=,这里不能用high = middle,会陷入死循环
            }
            else{
                low = middle - 1;
            }
        }
        int targetAtRow = low;
        // 说明矩阵中没有target
        if(targetAtRow == -1){
            return false;
        }
        // 在target所在的行中用二分查找
        int left = 0, right = matrixCols - 1;
        while(left <= right){
            int middle = (right - left) / 2 + left;
            if(matrix[targetAtRow][middle] == target){
                return true;
            }
            else if(matrix[targetAtRow][middle] < target){
                left = middle + 1;
            }
            else{
                right = middle - 1;
            }
        }
        return false;
    }
};

你可能感兴趣的:(leetcode,矩阵,算法,leetcode,c++,二分查找)