首页 > 代码库 > LeetCode: Search a 2D Matrix [074]

LeetCode: Search a 2D Matrix [074]

【题目】


Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

[
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]

Given target = 3, return true.



【题意】

    给定一个mXn的矩阵,这个矩阵的每一行从左到右升序排序,每行的第一个值都比上一行的最后一个值大
    给定一个值,判断该值是否在矩阵中。


【思路】

       

        二维矩阵可以通过坐标的运算转化为一维数组,根据题意,这个二维矩阵等价于一个有序的数组
        使用二叉搜索即可求解


【代码】

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