74. Search a 2D Matrix

你快乐吗?

Posted by bbkgl on September 26, 2019

# 74. Search a 2D Matrix


98.74%,对二维数组进行二分查找。

  • 将二维数组看作一维数组
  • 通过整除和取模得到mid在二维数组的下标
  • 再进行普通的二分查找,可以用循环,也可以递归。
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();
        return binSearch(0, n * m - 1, target, matrix, n);
    }
     
    bool binSearch(int left, int right, int &target, vector<vector<int>> &matrix, int &n) {
        if (left > right) return false;
        int mid = (left + right) / 2;
        int midRow = mid / n, midCol = mid % n;
        if (matrix[midRow][midCol] < target)
            return binSearch(mid + 1, right, target, matrix, n);
        else if (matrix[midRow][midCol] > target)
            return binSearch(left, mid - 1, target, matrix, n);
        else return true;
    }
};