Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 240 · 2D Matrix

Search a 2D Matrix II

LeetCode 240 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Staircase search from the bottom-left.

ಮಧ್ಯಮArrayBinary SearchDivide and ConquerMatrix
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Search a 2D Matrix II (LeetCode 240) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — 2D Matrix ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Start at the bottom-left corner. Everything above is smaller and everything to the right is larger, so each comparison rules out a whole row or a whole column.

Approach

  1. 1

    row = m − 1, col = 0.

  2. 2

    Equal → found.

  3. 3

    Too big → move up; too small → move right.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Staircase searchPythonO(m+n) time · O(1) space
class Solution:
    #TC - O(M+N), SC - O(1)
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        m =len(matrix)
        n = len(matrix[0])
        #array is sorted from top to bottom and left to right
        #search from top bottom left 
        #rule - if current cell value is greater than the target row --
        #if the current cell is is less than the target col++
        row = m-1
        col =0
        while col<n and row>=0:
            if matrix[row][col]==target:
                return True
            if matrix[row][col]>target:
                row=row-1
            elif matrix[row][col]<target:
                col = col+1
        return False

    
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Search a 2D Matrix II — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Search a 2D Matrix II ಹಿಂದಿನ intuition ಏನು?

Start at the bottom-left corner. Everything above is smaller and everything to the right is larger, so each comparison rules out a whole row or a whole column.

Search a 2D Matrix II (LeetCode 240) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. row = m − 1, col = 0. 2. Equal → found. 3. Too big → move up; too small → move right.

Search a 2D Matrix II ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(m + n). Space: O(1). (Accepted approach: Staircase search.)

Search a 2D Matrix II ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Starting at the top-left gives no information — both directions increase.