240. 搜索二维矩阵 II

一、题目

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

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

二、思路

数组从左到右和从上到下都是升序的,如果从右上角出发开始遍历呢?

三、代码

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

四、分析

时间复杂度就是每个节点最多遍历一遍了,O(m + n)

posted @ 2023-03-05 16:40  ImreW  阅读(8)  评论(0编辑  收藏  举报