首页 > 代码库 > Search a 2D Matrix

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 = http://www.mamicode.com/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