Say I’m given a 2d array where all the numbers in the array are in increasing order from left to right and top to bottom.
What is the best way to search and determine if a target number is in the array?
//Starting from the top-right, if target is smaller then go left, if it is larger then go down
public boolean search2DMatrix(int[][] matrix, int target) {
int row = 0, col = matrix[0].length-1;
while (row < matrix.length && col >= 0) {
if (matrix[row][col] == target) return true;
else if (matrix[row][col] < target) row++;
else col--;
}
return false;
}