一个二分法查找二维数组的程序题
public class Search2DMatrix {
public static void main(String[] args){
int[][] matrix = new int[][]{{1, 3, 5, 7},{10, 11, 16, 20},{23, 30, 34, 50}};
System.out.println(searchMatrix(matrix, 10));
}
public static boolean searchMatrix(int[][] matrix, int target) {
for(int i = 0;i<matrix.length;i++){
int begin = 0;
int end = matrix[i].length-1;
while(begin <= end){
int middle = (begin + end)/2;
if(target < matrix[i][middle]){
end = middle-1;
//System.out.println("no found1"); 用来跟踪定位
}else
if(target > matrix[i][middle]){
begin = middle+1;
//System.out.println("no found2"); 用来跟踪定位
}else
return true;
}
}
return false;
}
}
当然查找一维数组更加简单。只需去掉第一个for循环即可。