LeetCode OJ-- Search a 2D Matrix

https://oj.leetcode.com/problems/search-a-2d-matrix/

具有数据递增性质的一个二维数组,对它进行二分搜索。

首先搜索target所在的行,再找列。

class Solution {
public:
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        if(matrix.size() == 0)
            return false;
        size_t col = matrix[0].size();
        if(col == 0)
            return false;
            
        //first find row
        int lowRow = 0, highRow = matrix.size() - 1;
        int targetRow = 0;
        while(lowRow <= highRow && highRow >=0 && lowRow< matrix.size())
        {
            int midRow = (lowRow + highRow)/2;
            if(target < matrix[midRow][0])
            {
                highRow = midRow - 1;
                if(highRow < 0)
                    return false;
            }
            else if(target == matrix[midRow][0] || target == matrix[midRow][col - 1])
                return true;
            else if(col!=1 && target < matrix[midRow][col - 1])
            {
                targetRow = midRow;
                break;
            }
            else
            {
                lowRow = midRow + 1;
                if(lowRow >= matrix.size())
                    return false;
            }
        }
        
        //find col binary search
        int lowCol = 0, highCol = col;
        while(lowCol <= highCol)
        {
            int midCol = (lowCol + highCol)/2;
            if(matrix[targetRow][midCol] == target)
                return true;
            else if(matrix[targetRow][midCol] < target)
                lowCol = midCol + 1;
            else
                highCol = midCol - 1;
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/qingcheng/p/3870560.html