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;
    }
};
相关推荐
青 春 记 忆1 小时前
LeetCode 53. 最大子数组和|Python 解法详解
python·算法·leetcode
星轨初途7 小时前
LeetCode 热题 100——day6 三数之和
数据结构·c++·算法·leetcode·职场和发展
鹿角片ljp7 小时前
LeetCode 53. 最大子数组和
算法·leetcode·职场和发展
mifengxing17 小时前
LeetCode 41.缺失的第一个正数|Hard题O(n)+O(1)最优解法深度解析
java·算法·leetcode·排序算法
hanlin0321 小时前
动态规划专练:力扣第121、122题
笔记·算法·leetcode
To_OC21 小时前
LC 74 搜索二维矩阵:换皮的二分查找,我居然一开始没看出来
javascript·算法·leetcode
玖玥拾1 天前
LeetCode 189 轮转数组
算法·leetcode
Tisfy1 天前
LeetCode 3345.最小可整除数位乘积 I:暴力枚举(从n开始尝试)
数学·算法·leetcode·题解·枚举
青山木1 天前
Hot 100 --- 在排序数组中查找元素的第一个和最后一个位置
java·数据结构·算法·leetcode
mifengxing1 天前
LeetCode 238 除自身以外数组的乘积|无除法O(n)时间+O(1)空间双解法
java·算法·leetcode