Search a 2D Matrix

Posted xpp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Search a 2D Matrix相关的知识,希望对你有一定的参考价值。

方法:采用二分查找的方法,注意rt = rows*cols-1;

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.size() == 0 || matrix[0].size() == 0) 
            return false;
        
        int rows = matrix.size(), cols = matrix[0].size();
        int lt = 0, rt = rows * cols-1;
        
        while(lt <= rt)
        {
            int mid = (lt + rt) / 2;
            int value = matrix[mid/cols][mid%cols];
            
            if(target == value)
                return true;
            if(target > value)
                lt = mid + 1;
            else
                rt = mid - 1;
        }
        
        return false;
    }
};

 

以上是关于Search a 2D Matrix的主要内容,如果未能解决你的问题,请参考以下文章

74. Search a 2D Matrix

74. Search a 2D Matrix

Search a 2D Matrix II

74. Search a 2D Matrix

74. Search a 2D Matrix

Search a 2D Matrix