Search a 2D Matrix II

medium array binary search matrix

Problem

Search for a value in an m×n matrix where each row is sorted left-to-right and each column is sorted top-to-bottom. Return true if found.

Inputmatrix shown below, target = 5
Outputtrue
Walk from the top-right: if cell > target step left, else step down. O(m + n).

def search_matrix(matrix, target):
    m, n = len(matrix), len(matrix[0])
    r, c = 0, n - 1
    while r < m and c >= 0:
        v = matrix[r][c]
        if v == target: return True
        if v > target: c -= 1
        else: r += 1
    return False
function searchMatrix(matrix, target) {
  const m = matrix.length, n = matrix[0].length;
  let r = 0, c = n - 1;
  while (r < m && c >= 0) {
    const v = matrix[r][c];
    if (v === target) return true;
    if (v > target) c--;
    else r++;
  }
  return false;
}
class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        int m = matrix.length, n = matrix[0].length;
        int r = 0, c = n - 1;
        while (r < m && c >= 0) {
            int v = matrix[r][c];
            if (v == target) return true;
            if (v > target) c--;
            else r++;
        }
        return false;
    }
}
bool searchMatrix(vector<vector<int>>& matrix, int target) {
    int m = matrix.size(), n = matrix[0].size();
    int r = 0, c = n - 1;
    while (r < m && c >= 0) {
        int v = matrix[r][c];
        if (v == target) return true;
        if (v > target) c--;
        else r++;
    }
    return false;
}
Time: O(m + n) Space: O(1)