[NeetCode 150] Search 2D Matrix

Search 2D Matrix

You are given an m x n 2-D integer array matrix and an integer target.

Each row in matrix is sorted in non-decreasing order.
The first integer of every row is greater than the last integer of the previous row.
Return true if target exists within matrix or false otherwise.

Can you write a solution that runs in O(log(m * n)) time?

Example 1:

Input: matrix = [[1,2,4,8],[10,11,12,13],[14,20,30,40]], target = 10

Output: true

Example 2:

Input: matrix = [[1,2,4,8],[10,11,12,13],[14,20,30,40]], target = 15

Output: false

Constraints:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 100
-10000 <= matrix[i][j], target <= 10000

Solution

This is a 2D binary search, all we need to do is modifying the middle position of 1D binary search. The time complexity is O(log⁡(n×m))=O(log⁡n+log⁡m)O(\log(n\times m))=O(\log n+\log m)O(log(n×m))=O(logn+logm).

It is also plausible to apply 1D binary search twice. In the first time we try to find the row and in the second time we try to find the column. The time complexity is also O(log⁡n+log⁡m)O(\log n+ \log m)O(logn+logm)

Code

Because the problem requires us to find an exact number, so it is better to use binary search in a closed interval.

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        n = len(matrix)
        m = len(matrix[0])
        le = 0
        ri = n*m-1
        mid = 0
        while le <= ri:
            mid = (le+ri)//2
            x = mid//m
            y = mid%m
            if matrix[x][y] == target:
                break
            if matrix[x][y] < target:
                le = mid+1
            else:
                ri = mid-1
        x = mid//m
        y = mid%m
        return matrix[x][y] == target

Open interval version:

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        n = len(matrix)
        m = len(matrix[0])
        le = 0
        ri = n*m
        while le < ri:
            mid = (le+ri)//2
            x = mid//m
            y = mid%m
            print(mid, x, y)
            if matrix[x][y] < target:
                le = mid+1
            else:
                ri = mid
        if le >= n*m:
            return False
        x = le//m
        y = le%m
        return matrix[x][y] == target
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ShadyPi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值