Search a 2D Matrix II

LeetCode Q 240 - Search a 2D Matrix II

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 in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

Solution

Begin our search at the top right corner of the matrix.

  • If the target is large than this number, then we find numbers below it.
  • If the target is small than this number, then we find numbers on the left of it.

Code:

public boolean searchMatrix(int[][] matrix, int target) {
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0)
        return false;
    int row = matrix.length, col = matrix[0].length;
    int r = 0, c = col - 1;
    while (r < row && c >= 0) {
        if (matrix[r][c] == target)
            return true;
        else if (matrix[r][c] < target)
            r++;
        else
            c--;
    }
    return false;
}

   Reprint policy


《Search a 2D Matrix II》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC