搜索二维矩阵

我们先来看题目描述:

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

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

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

相关推荐
!停12 分钟前
C语言单链表
c语言·数据结构·算法
闻缺陷则喜何志丹23 分钟前
【回文 字符串】3677 统计二进制回文数字的数目|2223
c++·算法·字符串·力扣·回文
Tisfy29 分钟前
LeetCode 0085.最大矩形:单调栈
算法·leetcode·题解·单调栈
mit6.82431 分钟前
出入度|bfs|状压dp
算法
hweiyu0032 分钟前
强连通分量算法:Kosaraju算法
算法·深度优先
源代码•宸32 分钟前
Golang语法进阶(定时器)
开发语言·经验分享·后端·算法·golang·timer·ticker
mit6.82438 分钟前
逆向思维|memo
算法
机器学习之心40 分钟前
MATLAB灰狼优化算法(GWO)改进物理信息神经网络(PINN)光伏功率预测
神经网络·算法·matlab·物理信息神经网络
代码游侠44 分钟前
学习笔记——ESP8266 WiFi模块
服务器·c语言·开发语言·数据结构·算法
倦王44 分钟前
力扣日刷26110
算法·leetcode·职场和发展