题目描述

链接: https://leetcode-cn.com/problems/search-a-2d-matrix-ii/submissions/

编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:

每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例:

现有矩阵 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]
]
给定 target = 5,返回 true。

给定 target = 20,返回 false。


题目分析

这道题不是严格的二分题, 但是可以根据题目中特殊的性质去卡这个数.
从右上角开始, 如果目标大于当前数, 由于在右上角, 当前行左边部分已经不可能比它大了, 所以行数 ++,
如果目标小于当前数, 同理, 列数--,
如果等于, 就返回 true, 表示已经找到.


代码

class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0 ||
           matrix[0] == null || matrix[0].length == 0) 
            return false;
        int m = matrix.length, n = matrix[0].length;
        int i = 0, j = n - 1; // 从右上角开始
        while (i < m && j >= 0) {
            if (target > matrix[i][j]) i++;
            else if (target < matrix[i][j]) j--;
            else return true;
        }
        return false;
    }
}