[LeetCode] 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:
    int m = 0, n = 0;
    vector<vector<int>> data;
    bool search(int left, int right, int target)
    {
        int mid = (right + left) / 2;
        if(right - left == 1) return target == data[left / n][left % n];
        else return search(left, mid, target) || search(mid, right, target);
    }
    bool searchMatrix(vector<vector<int> > &matrix, int target) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(matrix.size() == 0) return false;
        data = matrix;
        m = matrix.size(), n = matrix[0].size();
        return search(0, m * n, target);
    }
};
原文地址:https://www.cnblogs.com/changchengxiao/p/3419273.html