zoukankan      html  css  js  c++  java
  • 二维数组中的查找一个数

    题目描述

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

    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);
    }
    }
  • 相关阅读:
    12-29 批量删除
    12-29 注册审核
    12-25造数据库面向对象
    12-23 会话保持
    2016-12-19 php修改数据库数据
    12-18数据访问
    12-16php测试题
    1027 制作表格
    1027 超链接
    1027 HTML
  • 原文地址:https://www.cnblogs.com/hujingwei/p/5022121.html
Copyright © 2011-2022 走看看