publicbooleansearchMatrix(int[][] matrix, int target){ if(matrix.length == 0 || matrix[0].length == 0) returnfalse; int row = matrix.length - 1; int col = matrix[0].length - 1; int left = 0; int right = row; while(left <= right){ int mid = left + (right - left) / 2; //如果元素大于mid行的最大值,则其一定出现于大于mid的行 if(target > matrix[mid][col]) left = mid + 1; //如果元素小于mid行的最小值,则其一定出现于小于mid的行 elseif(target < matrix[mid][0]) right = mid - 1; //否则,元素存在于mid行,在该行中进行二分查找 else return binsearch(matrix[mid], target); } returnfalse; }
//此函数在数组num中查找元素target publicbooleanbinsearch(int[] num, int target){ int n = num.length; int left = 0; int right = n - 1; while(left <= right){ int mid = left + (right - left) / 2; if(target == num[mid]) returntrue; elseif(target > num[mid]) left = mid + 1; else right = mid - 1; } returnfalse; }