搜索二维矩阵

我们先来看题目描述:

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

复制代码
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 小的话往下走。

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

相关推荐
爱炼丹的James2 分钟前
第三章 搜索和图论
数据结构·算法·图论
菜菜笔记3 分钟前
【无标题】
算法
努力努力再努力wz8 分钟前
【QT入门系列】QWidget 六大常用属性详解:windowOpacity、cursor、font、focus、toolTip 与 styleSheet
android·开发语言·数据结构·c++·qt·mysql·算法
Gauss松鼠会15 分钟前
GaussDB(DWS) 资源监控Topsql
java·网络·数据库·算法·oracle·性能优化·gaussdb
夏日听雨眠15 分钟前
数据结构(快速排序)
java·数据结构·算法
薇茗17 分钟前
【初阶数据结构】 升沉有序的平仄 排序 3
c语言·开发语言·数据结构·算法·排序算法·文件归并排序
薇茗19 分钟前
【初阶数据结构】 升沉有序的平仄 排序 2
c语言·数据结构·算法·排序算法·快排精讲
AI科技星24 分钟前
强哥德巴赫猜想(1+1)终极证明(2026 年5月 21 日)
开发语言·人工智能·算法·计算机视觉·量子计算
人道领域24 分钟前
【LeetCode刷题日记】654.最大二叉树:递归算法详解
java·算法·leetcode
Controller-Inversion28 分钟前
105. 从前序与中序遍历序列构造二叉树
数据结构·算法