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.

Solution

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;
        if ( target < matrix[0][0] or target > matrix[m-1][n-1] ) return false;
        int l = 0, r = m-1, mid = (l+r)/2;
        while ( l < r ) {
            mid = (l+r)/2;
            if ( target <= matrix[mid][n-1] ) r = mid;
            else {  
                if ( target >= matrix[mid+1][0] ) l = mid+1;
                else return false;
            }
        }
        int row = l;
        l = 0;
        r = n-1;
        cout << row << endl;
        if ( target == matrix[row][0] or target == matrix[row][n-1] ) return true;
        while ( l < r-1 ) {
            mid = (l+r)/2;
            if ( target == matrix[row][mid] ) return true;
            if ( target < matrix[row][mid] ) r = mid;
            else l = mid;
        }
        return false;
    }
};

Notes
Be careful with a lot of details!

results matching ""

    No results matching ""