Skip to content

Instantly share code, notes, and snippets.

@sdpatil
Created August 14, 2017 15:41
Show Gist options
  • Save sdpatil/1b785b8cb9f9229f152e38407dc60e71 to your computer and use it in GitHub Desktop.
Save sdpatil/1b785b8cb9f9229f152e38407dc60e71 to your computer and use it in GitHub Desktop.
Search in a 2D sorted array
/**
* Problem: Search a number in 2D matrix
*/
public class MatrixSearch {
/*
Solution: - Start by comparing with last column in first row, if the value matches return it
if not if target is smaller than current column go to next row if target is more than current
value go one column inward
*/
public boolean matrixSearch(int[][] A, int k) {
int row = 0;
int col = A[0].length - 1;
while (row < A.length && col >= 0) {
if (A[row][col] == k) {
return true;
} else if (A[row][col] < k) {
row = row + 1;
} else {
col = col - 1;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment