您的位置:首页 > 其它

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

2015-04-03 14:33 369 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: