首页 > 技术文章 > 【LeetCode-数组】搜索二维矩阵 II

flix 2020-06-17 23:23 原文

题目描述

编写一个高效的算法来搜索 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。

思路

《剑指Offer》原题。从右上角或者左下角开始搜索。假设从右上角 matrix[r][c]开始搜索:

  • 如果 r<rows && c >=0:
    • 如果当前元素等于 target,则返回 true;
    • 如果当前元素大于 target,则右移一步;
    • 如果当前元素小于 target,则下移一步;
  • 返回 false;

代码如下:

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        if(matrix.empty()) return 0; // 防止输入是 [[]]
        int rows = matrix.size();
        int cols = matrix[0].size();
        if(rows==0 || cols==0) return false;   //防止输入是 [[1]]

        int r = 0;
        int c = cols-1;
        while(r<rows && c>=0){
            if(matrix[r][c]==target) return true;
            if(matrix[r][c]>target) c--;
            else if(matrix[r][c]<target) r++;
        }
        return false;
    }
};
  • 时间复杂度:O(rows*cols)
  • 空间复杂度:O(1)

推荐阅读