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.