• 二维数组中的查找


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

    如 二维矩阵 1  2  8  9

                    2  4  9  12

                    4  7  10  13

                    6  8  11  15

    思路:如果一个数大于该整数则它同列下排的数都会比该整数大,同理如果比该整数小,它同排前列都比该整数小。

    从右上角开始:

    public boolean find(int[][] maxtrix,int target)
    {
      boolean found = false;
      if(maxtrix!=null)
        {

          int row =0;
          int column =maxtrix[0].length-1;
          while(row<maxtrix.length&&column>=0){
            if(maxtrix[row][column]==target){found =true;break;}
            else if(maxtrix[row][column]>target) --column;
            else ++row;
          }

        }
    return found;
    }

    从左下角:

    public boolean find2(int[][] maxtrix,int target)
    {
      boolean found = false;
      if(maxtrix!=null)
      {

                int column =0;

           int row =maxtrix.length-1;
        while(row>=0&&column<maxtrix[0].length){
        if(maxtrix[row][column]==target){found =true;break;}
        else if(maxtrix[row][column]>target) row--;
        else column++;
              }

         }
    return found;
    }

    测试用例:

    二维数组中能查到的数字:最大值(15),最小值(1),两者之间(7)

    二维数组中能查不到到的数字:大于最大值(16),小于最小值(0),两者之间(5)

    特殊输入:数组为空   

  • 相关阅读:
    String方法
    多态
    观察者模式
    ArrayList和LinkList
    唐岛湾
    AForge.Net C#的操作视频,照片读写功能
    JqGrid填坑
    日常点滴
    日常点滴
    EF Core 填坑记录
  • 原文地址:https://www.cnblogs.com/moxia1234/p/4013551.html
Copyright © 2020-2023  润新知