leetcode 74. Search a 2D Matrix

题目描述

要求时间复杂度必须是log(m*n)。那么对每一行分别执行二分查找就不符合要求,这种做法的时间复杂度是m*log(n)。

方法一,对每一行分别执行二分查找:

cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size();
        int n = matrix[0].size();
        for(int i = 0;i < m;i++){
            if(binary_search(matrix[i],0,n-1,target))
                return true;
        }
        return false;
    }

    bool binary_search(vector<int> row,int left,int right,int target){
        int mid = 0;
        while(left <= right){
            mid = left + ((right-left)>1);
            if(row[mid] == target)
                return true;
            else if(row[mid] > target){
                right = mid-1;
            }else{
                left = mid+1;
            }
        }
        return false;
    }
};

方法二,对整个矩阵执行二分查找,关键是要将整体的序号映射到行和列的下标:

时间复杂度log(m*n),符合要求。

cpp 复制代码
class Solution {
public:
    bool searchMatrix(vector<vector<int>>& matrix, int target) {
        int m = matrix.size();
        int n = matrix[0].size();
        int left = 0;
        int right = m*n-1;
        int mid = 0;
        int row = 0;
        int column = 0;
        while(left<=right){
            mid = left+((right-left)>>1);
            row = mid/n;
            column = mid%n;
            if(matrix[row][column] == target)
                return true;
            else if(matrix[row][column] > target)
            {
                right = mid -1;
            }else{
                left = mid + 1;
            }
        }
        return false;
    }
};
相关推荐
快去睡觉~2 小时前
力扣48:旋转矩阵
算法·leetcode·矩阵
卡洛斯(编程版3 小时前
(1) 哈希表全思路-20天刷完Leetcode Hot 100计划
python·算法·leetcode
MrZhangBaby5 小时前
SQL-leetcode—3374. 首字母大写 II
linux·sql·leetcode
自信的小螺丝钉6 小时前
Leetcode 343. 整数拆分 动态规划
算法·leetcode·动态规划
Q741_1476 小时前
C++ 力扣 438.找到字符串中所有字母异位词 题解 优选算法 滑动窗口 每日一题
c++·算法·leetcode·双指针·滑动窗口
圣保罗的大教堂17 小时前
leetcode 2348. 全 0 子数组的数目 中等
leetcode
Tisfy20 小时前
LeetCode 837.新 21 点:动态规划+滑动窗口
数学·算法·leetcode·动态规划·dp·滑动窗口·概率
tkevinjd1 天前
图论\dp 两题
leetcode·动态规划·图论
1白天的黑夜11 天前
链表-2.两数相加-力扣(LeetCode)
数据结构·leetcode·链表