剑指offer之第一题 二维数组中查找 Java实现

来源:互联网 发布:淘宝会员名怎么修改吗 编辑:程序博客网 时间:2024/05/21 22:23

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


package fenshujs;


import java.util.Scanner;


public class Janzhioffer {
/*
 * 剑指offer第一题  二维数组中的查找
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
       Scanner sc = new Scanner(System.in);
       int n = sc.nextInt();
       int m = sc.nextInt();
       int[][] a = new int[n][m];
       for(int i = 0;i<n;i++)
      for(int j = 0;j<m;j++)
      {
      a[i][j] = sc.nextInt();
      }
       System.out.println("please input the number that you want find:");
       int target = sc.nextInt();
       int k = 0;
       while(a[k][m-1] != target&&k<n&&m>0)
       {
      if(target>a[k][m-1])
      {
      k++;
      }
      else
      {
      m--;
      }
       }
       if(a[k][m-1] == target)
       {
      System.out.println("Yes");
       }
       else
       {
      System.out.println("No");
       }
}


}



输入输出

4 4
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
please input the number that you want find:
10
Yes

阅读全文
0 0
原创粉丝点击