[LinkedIn] Find target number in 2D sorted array (matrix)

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;
}
posted on 2015-04-03 14:33  Seth_L  阅读(102)  评论(0编辑  收藏  举报