搜索二维矩阵

我们先来看题目描述:

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

复制代码
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 小时前
ART配对软件使用
开发语言·c++·qt·算法
qq_513970442 小时前
力扣 hot100 Day56
算法·leetcode
PAK向日葵3 小时前
【算法导论】如何攻克一道Hard难度的LeetCode题?以「寻找两个正序数组的中位数」为例
c++·算法·面试
爱喝矿泉水的猛男5 小时前
非定长滑动窗口(持续更新)
算法·leetcode·职场和发展
YuTaoShao5 小时前
【LeetCode 热题 100】131. 分割回文串——回溯
java·算法·leetcode·深度优先
YouQian7726 小时前
Traffic Lights set的使用
算法
go54631584657 小时前
基于深度学习的食管癌右喉返神经旁淋巴结预测系统研究
图像处理·人工智能·深度学习·神经网络·算法
aramae7 小时前
大话数据结构之<队列>
c语言·开发语言·数据结构·算法
大锦终8 小时前
【算法】前缀和经典例题
算法·leetcode
想变成树袋熊8 小时前
【自用】NLP算法面经(6)
人工智能·算法·自然语言处理