Tensorum
YouTubeகற்கத் தொடங்குங்கள்
LeetCode 74 · 2D Matrix

Search a 2D Matrix

LeetCode 74 · நடுத்தரம் · தீர்வு, intuition & படிப்படியான வாக்த்ரூ

Treat the matrix as a flat sorted array.

நடுத்தரம்ArrayBinary SearchMatrix
LeetCode இல் திற ↗

நான் Search a 2D Matrix (LeetCode 74) ஐ இப்படித் தீர்த்தேன் — 2D Matrix பேட்டர்னின் ஒரு நடுத்தரம் பிராப்ளம். கீழே: intuition, படிப்படியான approach, என் accepted Python கோட், animated test cases மற்றும் line-by-line debugger.

கீழேயுள்ள விளக்கம் ஆங்கிலத்தில் உள்ளது.

Intuition

Each row continues where the previous one ended, so the whole matrix is one sorted list in disguise. Binary search over indices 0..m·n−1 and convert each index to (row, col) = (i // n, i % n).

Approach

  1. 1

    low = 0, high = m·n − 1.

  2. 2

    mid → row = mid // n, col = mid % n.

  3. 3

    Standard binary-search comparisons.

நான் எப்படித் தீர்த்தேன்

Flattened binary searchPythonO(log mn) time
class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        #represent 0 to m*n-1 list/array
        m = len(matrix)
        n = len(matrix[0])
        low = 0
        high = m*n-1
        while low<=high:
            mid = (low+high)//2
            row = mid//n
            col = mid%n
            if matrix[row][col]==target:
                return True
            elif matrix[row][col]>target:
                high = mid-1
            else:
                low = mid+1
        return False
ஸ்டெப்-த்ரூ ஏற்றுகிறது…

Search a 2D Matrix — அடிக்கடி கேட்கப்படும் கேள்விகள்

Search a 2D Matrix பின்னாலுள்ள intuition என்ன?

Each row continues where the previous one ended, so the whole matrix is one sorted list in disguise. Binary search over indices 0..m·n−1 and convert each index to (row, col) = (i // n, i % n).

Search a 2D Matrix (LeetCode 74) ஐ எப்படித் தீர்ப்பது?

1. low = 0, high = m·n − 1. 2. mid → row = mid // n, col = mid % n. 3. Standard binary-search comparisons.

Search a 2D Matrix இன் time மற்றும் space complexity என்ன?

Time: O(log(m·n)). Space: O(1). (Accepted approach: Flattened binary search.)

Search a 2D Matrix இல் பொதுவான தவறுகள் என்ன?

Divide by the number of columns, not rows.