imashutosh51

Search in a matrix whose elements are sorted in insertion order

Aug 11th, 2022 (edited)
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.68 KB | None | 0 0
  1. from typing import List
  2. class Solution:
  3.     def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
  4.         left = 0
  5.         right = len(matrix) * len(matrix[0]) - 1
  6.        
  7.         rows = len(matrix)
  8.         cols = len(matrix[0])
  9.        
  10.         while left <= right:
  11.             mid = (left + right) // 2
  12.            
  13.             row_idx = mid // cols
  14.             col_idx = mid % cols
  15.            
  16.             value = matrix[row_idx][col_idx]
  17.            
  18.             if value == target:
  19.                 return True
  20.             elif value > target:
  21.                 right = mid - 1
  22.             else:
  23.                 left = mid + 1
  24.        
  25.         return False
Advertisement
Add Comment
Please, Sign In to add comment