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

    题目描述

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

    思路

      在二维数组中,是有序的,从左下角开始查找,往上是递减,往右是递增,如下面的二维数组

           1   2  3  4  5

           2  3  4  5  6

       3  4  5  6  7

       4  5  6  7  8

       5  6  7  8  9

          代码如下

    package com.algorithm;
    
    import java.util.Scanner;
    
    /**
     * 在二维数组中的查找
     * 在一个二维数组中,每一行都按照从左到右递增
     * 的顺序排序,每一列都按照从上到下递增的顺序排序
     * @日期: 2018年6月7日 下午9:46:34
     * @作者: Chendb
     */
    public class TwoArray {
        
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            // 矩阵大小
            int number = scanner.nextInt();
            
            //定义矩阵
            int[][] matrix = new int[number][number];
            for (int i = 0 ; i < number ; i++){
                for (int j = 0 ; j < number ; j++) {
                    matrix[i][j] = scanner.nextInt();
                }
            }
            
            //需要查找的数字
            int target = scanner.nextInt();
            
            //输出矩阵
            for (int i = 0 ; i < number ; i++){
                for (int j = 0 ; j < number ; j++) {
                    System.out.print(matrix[i][j] + "	");
                }
                System.out.println("");
            }
            
            //是否存在
            boolean isExist = find(target,matrix);
            System.out.println("是否存在:" + (isExist ? "是" : "否"));
        }
    
        public static boolean find(int target, int [][] array) {
            
            //判断二维数组是否为空
            if (array == null || array.length == 0 || (array.length == 1 && array[0].length == 0)) {
                return false;
            }
            
            //行数
            int rows = array.length;
            //列数
            int cols = array.length;
            
            int i = rows - 1;
            int j = 0;
            
            // 在矩阵中,从左下角开始查找,往上递减,往右递增
            while (i >= 0 && j < cols){
                
                if (target == array[i][j]) { // 如果相等,则返回true
                    return true;
                }else if (target < array[i][j]) { // 如果小于,则往上找
                    i--;
                }else { // 如果大于,则往右找
                    j++;
                }
            }
            
            return false;
        }
        
    }
    View Code
  • 相关阅读:
    做题遇到的问题集合
    常见算法和数据结构存在的坑(updating)
    Loj#2090. 「ZJOI2016」旅行者(网格图分治)
    洛谷P3332 [ZJOI2013]K大数查询(整体二分板题)
    dij费用流模板
    KM求每个大小的匹配的最优解 模板
    JZOJ 5067. 【GDOI2017第二轮模拟day2】有理有据题 (KD-tree+历史最值问题)
    Codeforces 1186F. Vus the Cossack and a Graph(欧拉回路)
    bzoj#2095. [Poi2010]Bridges(二分+混合图欧拉回路)
    二维最小乘积生成树模板
  • 原文地址:https://www.cnblogs.com/cdblogs/p/9153148.html
Copyright © 2011-2022 走看看