您的位置:首页 > 其它

240. Search a 2D Matrix II

2016-07-30 01:02 281 查看
discuss里面的方法,最先把坐标放在格子的右上角。

如果当前格子比target小,那么就把col往左移动,因为已经是排好序了的,所有右边的都比它大

如果当前格子比target大,就把row往下移,因为上面行的都比它小

否则(即相等),就返回true;

public boolean searchMatrix(int[][] matrix, int target) {
if(matrix.length == 0 || matrix[0].length == 0) {
return false;
}
int row = 0;
int col = matrix[0].length - 1;
while(row < matrix.length && col >= 0) {
if(target == matrix[row][col]) {
return true;
} else if(target < matrix[row][col]) {
col--;
} else {
row++;
}
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: