Search a 2D Matrix Leetcode #74 题解[Python]

27 篇文章 1 订阅
24 篇文章 0 订阅

题目来源


https://leetcode.com/problems/search-a-2d-matrix/description/

题目描述


Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.

Example 1:

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

Example 2:

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

给出一个矩阵, 每行都是升序排列的, 而且保证第 i+1 行的第一个元素大于第 i 行的最后一个元素.

解题思路


这不过是一个二维数据结构的查找而已, 查找最简单高效的方法便是二分法.

我们只需先用第一次二分查找找出元素可能会在哪一行, 再用第二次二分查找找出元素可能在哪一具体位置即可.

代码实现


class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        M=len(matrix)
        if M==0:
            return False
        N = len(matrix[0])
        if N==0:
            return False
        lo=0
        hi=M-1
        while lo<=hi:
            mid=int((lo+hi)/2)
            if matrix[mid][0]==target:
                return True
            elif matrix[mid][0]>target:
                hi=mid-1
            else:
                lo=mid+1

       # print(lo,hi)
        if lo==0 or lo==M+1:
            return False

        temp=hi
        lo=0
        hi=N-1

      #  print(temp,mid)
        while lo<=hi:
            mid=int((lo+hi)/2)
            if matrix[temp][mid]==target:
                return True
            elif matrix[temp][mid]>target:
                hi=mid-1
            else:
                lo=mid+1

        return False

代码表现


看到代码表现的很优秀, 博主表示很开心( ̄▽ ̄)~*
74_ac

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值