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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| package algorithm;
public class SearchA2dMatrix {
public static boolean searchMatrix(int[][] matrix, int target) {
int row = matrix.length; int col = matrix[0].length;
int rowLow = 0; int rowHigh = row - 1; int midRow = 0; while (rowLow <= rowHigh) { midRow = (rowLow + rowHigh) / 2; if (matrix[midRow][0] == target) { return true; } else if (matrix[midRow][0] > target) { rowHigh = midRow - 1; } else { rowLow = midRow + 1; } } if (matrix[midRow][0] > target) { midRow -= 1; }
if (midRow < 0) { return false; }
int colLeft = 0; int colRight = col - 1; int midCol; while (colLeft <= colRight) { midCol = (colLeft + colRight) / 2; if (matrix[midRow][midCol] == target) { return true; } else if (matrix[midRow][midCol] > target) { colRight = midCol - 1; } else { colLeft = midCol + 1; } }
return false; }
public static void main(String[] args) {
int[][] matrix = new int[][]{{1,3,5,7}, {10,11,16,20}, {23,30,34,60}}; int target = 3; System.out.println(searchMatrix(matrix, target));
matrix = new int[][]{{1,3,5,7}, {10,11,16,20}, {23,30,34,60}}; target = 13; System.out.println(searchMatrix(matrix, target)); } }
|