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

[LeetCode] Search a 2D Matrix

Search a 2D Matrix

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.

解题思路:

题意为给定一个矩阵和一个目标值,推断目标值是否在矩阵中存在。矩阵满足:每一行从左往右递增,后一行的第一个元素大于前一行最后一个元素。

能够考虑二分查找法。将一维坐标转化成二维坐标就可以。

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        //二分查找,将矩阵查找转化成线性查找
        int m = matrix.size();
        if(m==0){
            return false;
        }
        int n = matrix[0].size();
        if(n==0){
            return false;
        }
        int start = 0, end = m*n-1;
        while(start<=end){
            int middle = (start + end)/2;
            int x = middle / n;
            int y = middle % n;
            if(matrix[x][y]==target){
                return true;
            }else if(matrix[x][y]<target){
                start = middle + 1;
            }else{
                end = middle - 1;
            }
        }
        return false;
    }
};


[LeetCode] Search a 2D Matrix