Search a 2D Matrix
LeetCode 74 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Treat the matrix as a flat sorted array.
ನಾನು 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
low = 0, high = m·n − 1.
- 2
mid → row = mid // n, col = mid % n.
- 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 FalseSearch 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.