• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
seven_hu
博客园    首页    新随笔    联系   管理    订阅  订阅

二维数组中的查找一个数

题目描述

在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数

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);
}
}
posted @ 2015-12-05 19:31  seven_hu  阅读(1767)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3