240. Search a 2D Matrix II - jiejackyzhang/leetcode-note GitHub Wiki

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.

For example,

Consider the following matrix:

[
  [1,   4,  7, 11, 15],
  [2,   5,  8, 12, 19],
  [3,   6,  9, 16, 22],
  [10, 13, 14, 17, 24],
  [18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

解题思路为利用矩阵的sorted特性,,每个submatrix左上角的元素都是最小的。 从矩阵右上角开始,若比target大,则target肯定不在这一列的右边(包括这一列),往左移一格; 若比target小,则target肯定不在这一行的左边,若存在,只可能在这个元素的左下submatrix中,因此往下移一格。 时间复杂度为O(m+n)。

public class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if(matrix == null || matrix.length == 0) return false;
        int row = 0, col = matrix[0].length - 1;
        while(row < matrix.length && col >= 0) {
            if(matrix[row][col] == target) {
                return true;
            } else if(matrix[row][col] > target) {
                col--;
            } else {
                row++;
            }
        }
        return false;
    }
}
⚠️ **GitHub.com Fallback** ⚠️