• 剑指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;
            }
        }
    
    }
    
  • 相关阅读:
    [AWS] Lab
    [AWS] Lab
    [AWS] Launch the VPC Wizard
    [AWS] EC2 Dashboard
    mysql .net下载
    币乎咕噜DeFi踩雷记
    量化分析师关于有限差分方法(FDM)最好的5本书
    QuantStart量化交易文集
    Exploring Market Making Strategy for High Frequency Trading: An Agent-Based Approach
    什么是信息比率?信息比率与夏普比率的差别?
  • 原文地址:https://www.cnblogs.com/lxr-xiaorong/p/14786297.html
Copyright © 2020-2023  润新知