剑指offer 数据结构与算法 二维数组查找 java 实现

来源:互联网 发布:在淘宝上怎么选紫砂壶 编辑:程序博客网 时间:2024/05/17 05:12

 应该注意java中二维数组的定义,以及使用方面与c中的区别

import java.util.Scanner;public class FindTwoSystemArray {    //查找函数public boolean find(int[][] array,int rows,int columns,int num){boolean found = false;if(array==null){System.out.println("数组为空");}if(array !=null & rows > 0 && columns > 0){int row = 0;int column = columns-1;while(row<rows &&column >= 0){int[] temp = array[row];//注意java中二维数组的使用与c中的不同if(temp[column]==num){found = true;break;//找到 退出循环}else if(temp[column] >num){column--;}else{row++;}}}return found;}public static void main(String[] args) {// TODO Auto-generated method stub         //初始化二维数组int num = 0;boolean found;FindTwoSystemArray find = new FindTwoSystemArray();int[][] array = new int[4][];         array[0] = new int[]{1,2,8,9,};         array[1] = new int[]{2,4,9,12};         array[2] = new int[]{4,7,10,13};         array[3] = new int[]{6,8,11,15};         Scanner scan = new Scanner(System.in);         System.out.println("请输入要求查找的数");         if(scan.hasNextInt()){        num = scan.nextInt();         }         found = find.find(array,4,4,num);         if(found==true){         System.out.println("找到该数");         }         else{System.out.println("找不到该数");         }         scan.close();                  }}


0 0
原创粉丝点击