Advertisement
imashutosh51

search in a matrix whose each row and column is sorted

Aug 11th, 2022 (edited)
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 KB | None | 0 0
  1. /*
  2. https://practice.geeksforgeeks.org/problems/search-in-a-matrix17201720/1
  3. Logic:
  4. remove a row or column in each comparison until an element is found.
  5. if top-right element is greater than x then we can't go downwards because
  6. whole column will have a greater elements so only one option left,go left
  7. side and same goes for each position of array.
  8. Time complexity: O(n+m)
  9. */
  10. class Solution{
  11. public:
  12.     int matSearch (vector <vector <int>> &arr, int n, int m, int x){
  13.         int i=0,j=m-1;
  14.         while(i<n && j>=0){
  15.             if(arr[i][j]>x){
  16.                 j--;
  17.             }
  18.             else if(arr[i][j]<x){
  19.                 i++;
  20.             }
  21.             else return 1;
  22.         }
  23.         return 0;
  24.     }
  25. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement