力扣 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;
    }
};
相关推荐
geats人山人海1 天前
算法基础第六讲 图论
算法·深度优先·图论
Rain的Java大神之路1 天前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
风落青芜1 天前
排序算法(四):归并排序、计数排序与算法总结
c语言·开发语言·数据结构·算法·排序算法
@陈小鱼1 天前
基于InceptionTime网络的PPG无创血压估计算法研究
人工智能·python·算法·回归·开源·ppg·血压估计
liulilittle2 天前
认识麻将 —— 流水及对账
算法·游戏·lua·对账·流水·资金·玩法
郝学胜-神的一滴2 天前
Effective Python 条款44:善用属性注解
开发语言·c++·vscode·python·算法·stl
青少儿编程课堂3 天前
第十八届蓝桥杯青少组图形化真题:校园分形雪花绘制解析(全国青少年信息素养大赛·电子学会图形化考级冲刺)
c++·python·算法·bfs·信息学竞赛
geovindu3 天前
python: KNeighborsClassifier K
开发语言·后端·python·算法