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;
    }
};
相关推荐
菥菥爱嘻嘻4 小时前
力扣面试150(42/150)
算法·leetcode·职场和发展
এ᭄画画的北北5 小时前
力扣-94. 二叉树的中序遍历
算法·leetcode
5 小时前
LeetCode Hot 100 搜索旋转排序数组
数据结构·算法·leetcode
设计师小聂!6 小时前
力扣热题100-------74.搜索二维矩阵
算法·leetcode·矩阵
菥菥爱嘻嘻8 小时前
力扣面试150(44/150)
javascript·leetcode·面试
姜不吃葱9 小时前
【力扣热题100】哈希——最长连续序列
算法·leetcode·哈希算法
蒟蒻小袁12 小时前
力扣面试150题--只出现一次的数字
数据结构·算法·leetcode
恣艺14 小时前
LeetCode 68:文本左右对齐
算法·leetcode·c#
Alfred king14 小时前
Leetcode 四数之和
算法·leetcode·职场和发展·数组·排序·双指针
এ᭄画画的北北1 天前
力扣-51.N皇后
算法·leetcode