Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Logic:
- If we start from top right then we will find that left side elements are smaller
- bottom side elements are bigger and we can reach at any element by comparing
- current elment with target.
- */
- class Solution {
- public:
- bool searchMatrix(vector<vector<int>>& matrix, int target) {
- int r=matrix.size(),c=matrix[0].size();
- int i=0,j=c-1;
- while(i<r && j>=0){
- if(matrix[i][j]==target) return true;
- else if(matrix[i][j]>target){
- j--;
- }
- else i++;
- }
- return false;
- }
- };
- #Python
- class Solution:
- def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
- i=0
- j=len(matrix[0])-1
- while i<len(matrix) and j>=0:
- if matrix[i][j]==target:
- return True
- if matrix[i][j]>target:
- j-=1
- else:
- i+=1
- return False
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement