1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import java.util.Arrays;
public class _74搜索二维矩阵 {
public boolean searchMatrix_binary(int[][] matrix, int target) { int rowsLen = matrix.length, colsLen = matrix[0].length; int len = rowsLen * colsLen; int left = 0, right = len; while (left < right) { int mid = (left + right) / 2; int x = mid / colsLen; int y = mid % colsLen; if (matrix[x][y] == target) return true; if (matrix[x][y] < target) left = mid + 1; else right = mid; } return false; }
public boolean searchMatrix_twice_binary(int[][] matrix, int target) { int rowsLen = matrix.length, colsLen = matrix[0].length; int[] colsNum = new int[rowsLen]; for (int i = 0; i < rowsLen; i++) colsNum[i] = matrix[i][colsLen - 1]; int rowIdx = Arrays.binarySearch(colsNum, target); if (rowIdx < 0) rowIdx = -(rowIdx + 1); int colIdx = Arrays.binarySearch(matrix[rowIdx], target); return colIdx >= 0; }
public static void main(String[] args) { _74搜索二维矩阵 searchMatrix = new _74搜索二维矩阵(); System.out.println(searchMatrix.searchMatrix_binary(new int[][]{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}, 15)); System.out.println(searchMatrix.searchMatrix_twice_binary(new int[][]{{1, 3, 5, 7}, {10, 11, 16, 20}, {23, 30, 34, 60}}, 15)); } }
|