题目链接
法一
public boolean searchMatrix(int[][] matrix, int target) {
if (matrix.length == 0) {
return false;
}
int row = 0, col = matrix[0].length - 1;
while (row < matrix.length && col >= 0) {
if (matrix[row][col] < target) {
row++;
} else if (matrix[row][col] > target) {
col--;
} else {
return true;
}
}
return false;
}
法二(二分)
public boolean searchMatrix_2(int[][] matrix, int target) {
int rowSize = matrix.length, colSize = matrix[0].length;
int left = 0, right = rowSize * colSize - 1;
int row, col;
while (left <= right) {
int mid = left + (right - left) / 2;
row = mid / colSize;
col = mid % colSize;
if (matrix[row][col] == target) {
return true;
} else if (matrix[row][col] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
本地测试
lay.showTitle(74);
Solution74 sol74 = new Solution74();
int[][] matrix74 = new int[][]{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}};
arrayOpt.showIntTwoDimArray(matrix74, matrix74.length);
System.out.println(sol74.searchMatrix(matrix74, 3));
System.out.println(sol74.searchMatrix_2(matrix74, 3));