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;
    }
};
相关推荐
YuTaoShao3 小时前
【LeetCode 每日一题】3634. 使数组平衡的最少移除数目——(解法一)排序+滑动窗口
算法·leetcode·排序算法
TracyCoder1235 小时前
LeetCode Hot100(27/100)——94. 二叉树的中序遍历
算法·leetcode
草履虫建模11 小时前
力扣算法 1768. 交替合并字符串
java·开发语言·算法·leetcode·职场和发展·idea·基础
VT.馒头16 小时前
【力扣】2721. 并行执行异步函数
前端·javascript·算法·leetcode·typescript
不穿格子的程序员20 小时前
从零开始写算法——普通数组篇:缺失的第一个正数
算法·leetcode·哈希算法
VT.馒头1 天前
【力扣】2722. 根据 ID 合并两个数组
javascript·算法·leetcode·职场和发展·typescript
执着2591 天前
力扣hot100 - 108、将有序数组转换为二叉搜索树
算法·leetcode·职场和发展
52Hz1181 天前
力扣230.二叉搜索树中第k小的元素、199.二叉树的右视图、114.二叉树展开为链表
python·算法·leetcode
苦藤新鸡1 天前
56.组合总数
数据结构·算法·leetcode
菜鸟233号1 天前
力扣647 回文子串 java实现
java·数据结构·leetcode·动态规划