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;
    }
};
相关推荐
Navigator_Z1 天前
LeetCode //C - 1033. Moving Stones Until Consecutive
c语言·算法·leetcode
We་ct1 天前
LeetCode 72. 编辑距离:动态规划经典题解
前端·算法·leetcode·typescript·动态规划
m0_629494731 天前
LeetCode 热题 100-----17.缺失的第一个正数
数据结构·算法·leetcode
Tisfy1 天前
LeetCode 0796.旋转字符串:暴力模拟
算法·leetcode·题解·模拟·字符串匹配
小雅痞2 天前
[Java][Leetcode middle] 209. 长度最小的子数组
java·算法·leetcode
浅念-2 天前
吃透栈:LeetCode 栈算法题全解析
数据结构·c++·算法·leetcode·职场和发展·
阿Y加油吧2 天前
二刷 LeetCode:62. 不同路径 & 64. 最小路径和 复盘笔记
笔记·算法·leetcode
承渊政道2 天前
【动态规划算法】(两个数组的DP问题深度剖析与求解方法)
数据结构·c++·学习·算法·leetcode·动态规划·哈希算法
加农炮手Jinx2 天前
LeetCode 26. Remove Duplicates from Sorted Array 题解
算法·leetcode·力扣
加农炮手Jinx2 天前
LeetCode 88. Merge Sorted Array 题解
算法·leetcode·力扣