74. 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 row = matrix.size();
        int col = matrix[0].size();

        int lb = 0;
        int ub = row*col - 1;

        while(ub >= lb){
            int mid = (lb + ub) >>1;

            if(matrix[mid / col][mid % col] == target)
                return true;
            else if(matrix[mid / col][mid % col] < target)
                lb = mid + 1;
            else
                ub = mid -1;
        }
        return false;
    }
};

results matching ""

    No results matching ""