查找某个整数是否在数组中(数组为有序)

针对本题,首先数组是有序的 例如:
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
输入任意一个整数 看这个整数是否在数组中,在返回true,否则返回false

package com.cn.hnust.TestPoj;

/**
 * @author dark
 * @date 2018.1.24
 * 求一个有顺序的二维数组,任意一个值,是否在数组中 ,在的话返回true 否则返回false
 */
public class TwoSZ {
    public static boolean find(int[][] array,int number){
        if(array==null){ //判断数组是否为空
            return false;
        }
        int column=array[0].length-1;//定义行和列
        int row=0;
        while (row<array.length && column>=0){
            if(array[row][column]==number){ //判断是否找到
                return true;
            }
            if(array[row][column]>number){//因为有序 所以从第一行最后一列开始,然后减少列增加行 ,依次对比
                column--;
            }else{
                row++;
            }
        }
        return false;
    }
    public static void main(String args[]){
        int[][] testarray=new int[4][4];
        testarray[0][0]=1;
        testarray[0][1]=2;
        testarray[0][2]=8;
        testarray[0][3]=9;
        testarray[1][0]=2;
        testarray[1][1]=4;
        testarray[1][2]=9;
        testarray[1][3]=12;
        testarray[2][0]=4;
        testarray[2][1]=7;
        testarray[2][2]=10;
        testarray[2][3]=13;
        testarray[3][0]=6;
        testarray[3][1]=8;
        testarray[3][2]=11;
        testarray[3][3]=15;
        System.out.println(find(testarray, 1));
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值