题目
给定一个有N*M的整型矩阵matrix和一个整数K, matrix的每一行和每一列都是排好序的。实现一个函数,判断K 是否在matrix中。要求时间复杂度为O(N+M),额外空间复杂度为O(1)。
例:0 1 2 5 2 3 4 7 4 4 4 8 5 7 7 9
如果K为7,返回true;如果K为6,返 回false。
代码
/**
* 查找
*
* @param matrix 目标矩阵
* @param target 目标值
* @return true/false
*/
private static boolean isContains(int[][] matrix, int target) {
int x = matrix[0].length - 1;
int y = 0;
while (x > -1 && y < matrix.length) {
if (matrix[y][x] == target) {
return true;
} else if (matrix[y][x] > target) {
x--;
} else {
y++;
}
}
return false;
}