力扣 74. 搜索二维矩阵

🔗 https://leetcode.cn/problems/search-a-2d-matrix

题目

  • 给一个二维矩阵,保证数字在每行从左到右都是非严格递增
  • 每一行的第一个数字大于上一行最后一个数字
  • 给一个 target,判断是否存在在二维矩阵中

思路

  • 先 binary search 定位到行,再 binary search 定位到列

代码

cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size();
        int n = matrix[0].size();
        int x, y, xx, yy;
        x = 0; y = 0; 
        xx = m - 1; yy = n - 1;
        int mid_x = (x + xx) / 2;
        while (x <= xx) {
            mid_x = (x + xx) / 2;
            if (matrix[mid_x][n - 1] < target) {
                x = mid_x + 1;
            }
            if (matrix[mid_x][0] > target) {
                xx = mid_x - 1;
            }

            if (matrix[mid_x][0] <= target && matrix[mid_x][n - 1] >= target)
                break;
        }

        if (matrix[mid_x][0] > target || matrix[mid_x][n - 1] < target) 
            return false;

        int mid_y = (y + yy) / 2;
        while (y <= yy) {
                int mid_y = (y + yy) / 2;
                if (matrix[mid_x][mid_y] == target) return true;
                if (matrix[mid_x][mid_y] < target) {
                    y = mid_y + 1;
                } else {
                    yy = mid_y - 1;
                }  
        }
        return false;
    }
};
相关推荐
格林威1 小时前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
程序员莫小特3 小时前
老题新解|大整数加法
数据结构·c++·算法
过往入尘土4 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.4 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
Dream it possible!4 小时前
LeetCode 面试经典 150_哈希表_存在重复元素 II(46_219_C++_简单)
leetcode·面试·散列表
蒙奇D索大4 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it
智驱力人工智能5 小时前
工厂抽烟检测系统 智能化安全管控新方案 加油站吸烟检测技术 吸烟行为智能监测
人工智能·算法·安全·边缘计算·抽烟检测算法·工厂抽烟检测系统·吸烟监测
学学学无无止境5 小时前
组合两个表-力扣
leetcode
程序员爱钓鱼5 小时前
Go语言实战案例——进阶与部署篇:编写Makefile自动构建Go项目
后端·算法·go
_Power_Y6 小时前
Java面试常用算法api速刷
java·算法·面试