leetcode.74:搜索二维矩阵

简介: leetcode.74:搜索二维矩阵

题目描述:


编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
·每行中的整数从左到右按升序排列。
·每行的第一个整数大于前一行的最后一个整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-a-2d-matrix
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


示例1:


输入:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 3
输出: true


示例2:


输入:
matrix = [
  [1,   3,  5,  7],
  [10, 11, 16, 20],
  [23, 30, 34, 50]
]
target = 13
输出: false


题目难度:中等


分析:


典型的二分算法,只不过普通的是一维数组,这个是二维数组。但是算法逻辑一样。代码如下:


java:


class Solution {
    public boolean searchMatrix(int[][] matrix, int target) {
        if (matrix.length == 0) {
            return false;
        }
        // 行
        int m = matrix.length;
        // 列
        int n = matrix[0].length;
        int left = 0;
        int right = m * n - 1;
        int index = 0;
        int element = 0;
        while (left <= right) {
            index = (left + right) / 2;
            // 如果把二维数组捋直,选取其中一个元素的下标作为index
            // 那么此元素在二维数组中可如下表示:
            element = matrix[index / n][index % n];
            if (element == target) {
                return true;
            } else if (element > target) {
                right = index - 1;
            } else {
                left = index + 1;
            }
        }
        return false;
    }
}


python:


class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        if len(matrix) == 0:
            return False
        m, n, index, element= len(matrix), len(matrix[0]), 0, 0
        left, right = 0, m * n - 1
        while left <= right:
            index = (left + right) // 2
            element = matrix[index // n][index % n]
            if element == target:
                return True
            elif element > target:
                right = index - 1
            else:
                left = index + 1
        return False


总结:

时间复杂度为:O(log(mn))。

目录
相关文章
|
19天前
|
算法
力扣240 搜索二维矩阵II
力扣240 搜索二维矩阵II
|
19天前
|
Go
golang力扣leetcode 240.搜索二维矩阵II
golang力扣leetcode 240.搜索二维矩阵II
23 0
|
19天前
|
Go
golang力扣leetcode 79.单词搜索
golang力扣leetcode 79.单词搜索
27 0
|
7月前
|
vr&ar
leetcode每日一题 2021/4/7 81. 搜索旋转排序数组 II
leetcode每日一题 2021/4/7 81. 搜索旋转排序数组 II
30 0
|
8月前
代码随想录Day16 LeetCode T654 最大二叉树 T617 合并二叉树 T700 二叉搜索树中的搜索
代码随想录Day16 LeetCode T654 最大二叉树 T617 合并二叉树 T700 二叉搜索树中的搜索
33 0
|
19天前
|
算法
【Leetcode 74】搜索二维矩阵 —— 二分查找|矩阵
给你一个满足下述两条属性的`m x n`整数矩阵:每行中的整数从左到右按非严格递增顺序排列。每行的第一个整数大于前一行的最后一个整数
|
19天前
|
算法 测试技术 C#
【二分查找】【z型搜索】LeetCode240:搜索二维矩阵
【二分查找】【z型搜索】LeetCode240:搜索二维矩阵
|
19天前
|
算法
leetcode-74:搜索二维矩阵
leetcode-74:搜索二维矩阵
26 0
|
19天前
|
算法
leetcode-240:搜索二维矩阵 II
leetcode-240:搜索二维矩阵 II
22 0
|
19天前
|
Go
golang力扣leetcode 81.搜索旋转排序数组II
golang力扣leetcode 81.搜索旋转排序数组II
20 0