leetcode--240. 搜索二维矩阵 II

  1. 搜索二维矩阵 II
    编写一个高效的算法来搜索 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。

思路:左下角标志数法

class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        int n = matrix.size();
        if (n == 0){
            return false;
        }
        int m = matrix[0].size();
        if (m == 0){
            return false;
        }
        int high = n - 1, wide = 0;
        while (high >= 0 && wide < m){
            if (matrix[high][wide] == target){
                return true;
            } else if (matrix[high][wide] < target){
                wide++;
            } else {
                high--;
            }
        }
        return false;
    }
};
/*36ms,15.4MB*/

时间复杂度:O(n+m)
空间复杂度:O(1)

发布了59 篇原创文章 · 获赞 0 · 访问量 1197

猜你喜欢

转载自blog.csdn.net/u011861832/article/details/104566953
今日推荐