Leecode240. 搜索二维矩阵 II——Leecode每日一题系列

Posted 来老铁干了这碗代码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leecode240. 搜索二维矩阵 II——Leecode每日一题系列相关的知识,希望对你有一定的参考价值。

我是小张同学,立志用更简洁的代码做更高效的表达


编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。

示例 1:
输入: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

示例 2:
输入: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 = 20
输出:false

提示:
m == matrix.length
n == matrix[i].length
1 <= n, m <= 300
-109 <= matrix[i][j] <= 109
每行的所有元素从左到右升序排列
每列的所有元素从上到下升序排列
-109 <= target <= 109


思路:从二维数组的右上角开始查找,每次筛选掉一行或一列。

细节:这里采用变量 t t t来代替 m a t r i x [ i ] [ j ] matrix[i][j] matrix[i][j],目的是减少时间消耗。 经过测试,大约可以减少20ms的时间消耗。

class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int row = matrix.size(), col = matrix[0].size();
        int i = 0, j = col - 1;
        while (i < row && j >= 0) {
            int t = matrix[i][j];
            if (target == t) return true;
            else if (target > t) i++;
            else if(target < t) j--;
        }
        return false;
    }
};

以上是关于Leecode240. 搜索二维矩阵 II——Leecode每日一题系列的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 240.搜索二维矩阵II

5-005-(LeetCode- 240) 搜索二维矩阵 II

240. 搜索二维矩阵 II

题目地址(2d-matrix-ii/“>240. 搜索二维矩阵 II)

240. 搜索二维矩阵 II

240. 搜索二维矩阵 II