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

 应该注意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();
         
         
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值