Created
August 14, 2017 15:41
-
-
Save sdpatil/1b785b8cb9f9229f152e38407dc60e71 to your computer and use it in GitHub Desktop.
Search in a 2D sorted array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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