zoukankan      html  css  js  c++  java
  • 剑指offer04--二维数组中的查找

    一、题目描述

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

    二、代码实现(参考画解剑指)

    import java.util.Scanner;
    
    /**
     * @Author: LXR
     * @Date: 2021/5/19 17:27
     */
    
    public class jianzhi04 {
        public static void main(String[] args) {
            Solution solution = new jianzhi04().new Solution();
            Scanner sc=new Scanner(System.in);
            System.out.println("请输入二维数组的行数:");
            int row=sc.nextInt();
            System.out.println("请输入二维数组的列数:");
            int col=sc.nextInt();
            int[][] matrix=new int[row][col];
            sc.nextLine();//跳过行列后的回车
            System.out.println("请输入二维数组元素:");
            for (int i = 0; i <row; i++) {
                for (int j = 0; j <col; j++) {
                    matrix[i][j]=sc.nextInt();
                }
            }
            System.out.println("请输入目标数字:");
            int target=sc.nextInt();
            boolean ints=solution.findNumberIn2DArray(matrix,target);
            System.out.println(ints);
        }
        class Solution {
            public boolean findNumberIn2DArray(int[][] matrix, int target) {
                //如果数组为空,那么直接判错
                if (matrix.length==0)
                    return false;
                //从矩阵左下角看,上方的数字都比其小,右方的数字都比其大--非常关键
                int x=0;//列标号
                //二维数组的行数matrix.length
                int y=matrix.length-1;//行标号
                //边界
                while (x<matrix[0].length&&y>=0){
                    //当前数字大于target时,找比当前数字小的,当前数字更新为其上面数字
                    if (matrix[y][x]>target){
                        y--;
                     //当前数字小于target时,找比当前数字大的,当前数字更新为其右侧数字
                    }else if (matrix[y][x]<target){
                        x++;
                     //当前数字等于target,返回true
                    }else {
                        return true;
                    }
                }
                //遍历到边界都没有找到对应的,返回false
                return false;
            }
        }
    
    }
    
  • 相关阅读:
    域名恶意指向的问题解决
    dedecms 空间迁移步骤
    PHP 字符串长度计算函数strlen() 正确的计算 中文汉字长度的方法 与mb_strlen()应用
    php模板 smarty
    PHP 中 字符串的 比较函数 strcmp() strcasecmp()
    织梦cms安装完成后登录后台出现空白。主要原因是php版本的问题
    VS2008安装VTk
    英文缩写
    java中native的用法
    On The Way
  • 原文地址:https://www.cnblogs.com/lxr-xiaorong/p/14786297.html
Copyright © 2011-2022 走看看