Skip to content

Instantly share code, notes, and snippets.

@zcwang
Created July 17, 2018 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zcwang/364a5e8bed4036c81069484faa50d405 to your computer and use it in GitHub Desktop.
Save zcwang/364a5e8bed4036c81069484faa50d405 to your computer and use it in GitHub Desktop.
Search 2D Matrix for target
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0) {
return false;
}
if (matrix[0].length == 0) {
return false;
}
int rowIndex = 0;
int colIndex = matrix[0].length - 1;
while (rowIndex < matrix.length && colIndex >= 0) {
if (matrix[rowIndex][colIndex] == target) {
return true;
}
if (target < matrix[rowIndex][colIndex]) {
colIndex--;
} else if (target > matrix[rowIndex][colIndex]) {
rowIndex++;
}
}
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment