Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Search a 2D matrix (Leetcode 240) #308

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions Medium/Search a 2D Matrix II.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row = 0;//Initially we are at integer 1 as per example 1
int col = matrix[0].length-1;//at element 15 as per example 1
while(row<matrix.length && col>=0){
if(target==matrix[row][col]){
return true;
}
if(target<matrix[row][col]){ // for example we are at row 0 and col 4
//means at 15 and 15>target so decrease column by 1 and check, here if we decrease by 1 we will be on 11
col--;
continue;
}
if(target>matrix[row][col]){
//moving forward we will end up at 4 which is lesser than target and
//as the matrix is sorted we won't get the element in that row so we will switch the row
row++;
}
}
return false; //if the target element is not present
}
}