imashutosh51

Search a 2D Matrix

Aug 11th, 2022 (edited)
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.67 KB | None | 0 0
  1. '''
  2. Logic:
  3. remove a row or column in each comparison until an element is found.
  4. if top-right element is greater than x then we can't go downwards because
  5. whole column will have a greater elements so only one option left,go left
  6. side and same goes for each position of array.
  7. Time complexity: O(n+m)
  8. '''
  9. class Solution:
  10.     def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
  11.         i=0
  12.         j=len(matrix[0])-1
  13.         while i<len(matrix) and j>=0:
  14.             if matrix[i][j]==target:
  15.                 return True
  16.             if matrix[i][j]>target:
  17.                 j-=1
  18.             else:
  19.                 i+=1
  20.         return False
  21.  
  22.        
Advertisement
Add Comment
Please, Sign In to add comment