搜索二维矩阵

我们先来看题目描述:

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

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

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

相关推荐
小月球~2 小时前
天梯赛 · 并查集
数据结构·算法
仍然.2 小时前
算法题目---模拟
java·javascript·算法
潇冉沐晴4 小时前
DP——背包DP
算法·背包dp
GIOTTO情5 小时前
2026 世界互联网大会亚太峰会|AI 时代媒介投放的技术实战与算法优化
人工智能·算法
逆境不可逃5 小时前
LeetCode 热题 100 之 543. 二叉树的直径 102. 二叉树的层序遍历 108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
算法·leetcode·职场和发展
计算机安禾5 小时前
【数据结构与算法】第19篇:树与二叉树的基础概念
c语言·开发语言·数据结构·c++·算法·visual studio code·visual studio
副露のmagic5 小时前
哈希章节 leetcode 思路&实现
算法·leetcode·哈希算法
csuzhucong5 小时前
puzzle(1037)黑白、黑白棋局
算法
XiYang-DING5 小时前
【LeetCode】链表 + 快慢指针找中间 | 2095. 删除链表的中间节点
算法·leetcode·链表
Zarek枫煜5 小时前
[特殊字符] C3语言:传承C之高效,突破C之局限
c语言·开发语言·c++·单片机·嵌入式硬件·物联网·算法