您的位置:首页 > 其它

二维数组中的查找一个数

2015-12-05 19:31 267 查看

题目描述

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数
public class solution1 {
public static boolean Find(int[][] array,int target){
//array的长度和宽度
int rows=array.length;
int cols=array[0].length;
//如果array不包含任何元素,就直接返回false
if(rows<=0||cols<=0){
return false;
}
//初始时temp在数组array中的位置
int row=0;
int col=cols-1;
//先找到二维数组的右上角的那个元素的值
int temp=array[row][col];
//如果temp与target不相等,那么就按照下面的规则,不断改变temp的值,直到相等
while (temp!=target){
//当temp大于target的时候,向左移动一个位置
if(temp>target){
col=col-1;
if(col<0){
return false;
}
}
//当temp小于target的时候,向下移动一个位置
if (temp<target){
row=row+1;
if (row>=rows){
return false;
}
}
//改变temp的值
temp=array[row][col];
}
return true;
}
public static void main(String[] args){
//int[][] array={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
int[][] array={{}};
int target=100;
boolean result=Find(array,16);
System.out.println(result);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: