搜索二维矩阵

我们先来看题目描述:

常规思路是进行二分查找,此时就能看到一个奇妙的解法,代码如下:

复制代码
class Solution {
public:
    bool searchMatrix(https://zhida.zhihu.com/search?content_id=214174621&content_type=Article&match_order=1&q=vector&zhida_source=entity<vector<int>>& matrix, int target) {
        if(matrix.size() == 0 || matrix[0].size() == 0) return false;
        int i = 0, j = matrix[0].size()-1; // start at the end of first row
        while(i < matrix.size() && j >= 0){ // initially, matrix[i][j] represents the max of each row
            if(matrix[i][j] == target) return true;
            if(matrix[i][j] < target) i++; // if max of row < target, move down a row
            else j--; // you're in the right row, so traverse backwards through the row
        }
        return false; 
    }
};

实际上,基本思路就是从矩阵第一行最右侧开始查找,当前值比 target 大往左走,比 target 小的话往下走。

好了,今天的文章分享就到这里了,希望对大家的学习有帮助哦!

相关推荐
IronMurphy43 分钟前
【算法四十三】279. 完全平方数
算法
墨染天姬1 小时前
【AI】Hermes的GEPA算法
人工智能·算法
papership1 小时前
【入门级-数据结构-3、特殊树:完全二叉树的数组表示法】
数据结构·算法·链表
smj2302_796826521 小时前
解决leetcode第3911题.移除子数组元素后第k小偶数
数据结构·python·算法·leetcode
Beginner x_u2 小时前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
_深海凉_5 小时前
LeetCode热题100-寻找两个正序数组的中位数
算法·leetcode·职场和发展
旖-旎6 小时前
深搜练习(电话号码字母组合)(3)
c++·算法·力扣·深度优先遍历
谭欣辰6 小时前
C++快速幂完整实战讲解
算法·决策树·机器学习
Mr_pyx6 小时前
【LeetHOT100】随机链表的复制——Java多解法详解
算法·深度优先
AIFarmer6 小时前
【无标题】
开发语言·c++·算法