1.二维数组中的查找
在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
适用数组res来标记一行中,是否不可能。使用了一个递归。
public class Solution {
public static boolean Find(int [][] array,int target) {
int row_len = array.length;
System.out.println(row_len);
int col_len = array[0].length;
if(row_len*col_len ==0){
return false;
}
int[][] res =new int[row_len][2];//记录头和尾巴
//初始化
for(int i =0;i<row_len;i++){
res[i][0]=-1;
res[i][1]=col_len;
}
return search(res,array,row_len,col_len,target,row_len/2,col_len/2);
}
public static boolean search(int[][] res,int[][] array,int row_len,int col_len,int target,int i,int j){
if(array[i][j] > target){
//更新res中的范围
biggerThanTarget(res,row_len,i,j);
//先左边,再上边
if(isOk(res,row_len,i,j-1)){
if( search(res,array,row_len,col_len,target,i,j-1))
return true;
}
if(isOk(res,row_len,i-1,j)){
if( search(res,array,row_len,col_len,target,i-1,j))
return true;
}
}else if(array[i][j] < target){
smallerThanTarget(res, i, j);
//先右边,再下边
if(isOk(res,row_len,i,j+1)){
if( search(res,array,row_len,col_len,target,i,j+1))
return true;
}
if(isOk(res,row_len,i+1,j)){
if( search(res,array,row_len,col_len,target,i+1,j))
return true;
}
}else{
return true;
}
return false;
}
public static boolean isOk(int[][] res,int row_len,int i,int j){
if(i==-1 || i==row_len){
return false;
}
return res[i][0] < j && res[i][1]>j;
}
public static void biggerThanTarget(int[][] res,int row_len,int i,int j){
for(int k=i; k <row_len;k++){
if( j < res[k][1]){
res[k][1] = j;
}
}
}
public static void smallerThanTarget(int[][] res,int i,int j){
for(int k=i; k >= 0;k--){
if( j > res[k][0] ){
res[k][0] = j;
}
}
}
}
public class Solution {
public boolean Find(int [][] array,int target) {
boolean found = false;
int lie = array[0].length;
int hang = array.length;
int column = lie -1;
int row =0;
while(row<hang &&column>=0){
int value = array[row][column];
if(target>value){
row++;
}else if(value>target){
column--;
}else{
found = true;
break;
}
}
return found;
}
}
看了别人的思路,觉得自己是个智障...