Advertisement
imashutosh51

Search a 2D matrix II

Oct 16th, 2022 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. /*
  2. Logic:
  3. If we start from top right then we will find that left side elements are smaller
  4. bottom side elements are bigger and we can reach at any element by comparing
  5. current elment with target.
  6. */
  7. class Solution {
  8. public:
  9.     bool searchMatrix(vector<vector<int>>& matrix, int target) {
  10.        int r=matrix.size(),c=matrix[0].size();
  11.        int i=0,j=c-1;
  12.        while(i<r && j>=0){
  13.            if(matrix[i][j]==target) return true;
  14.            else if(matrix[i][j]>target){
  15.                j--;
  16.            }
  17.            else i++;
  18.        }
  19.        return false;
  20.     }
  21. };
  22.  
  23. #Python
  24. class Solution:
  25.     def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
  26.         i=0
  27.         j=len(matrix[0])-1
  28.         while i<len(matrix) and j>=0:
  29.             if matrix[i][j]==target:
  30.                 return True
  31.             if matrix[i][j]>target:
  32.                 j-=1
  33.             else:
  34.                 i+=1
  35.         return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement