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

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

    • resolution 1:

       resolution1 是一个比较容易想到的方法,依次从每行每列遍历整个数组直到找到和target相同的数为止

    //运行时间:198ms
    
    //占用内存:17364k
    public class Solution {
        public boolean Find(int target, int [][] array) {
            int rowCount = array.length;
            int colCount = array[0].length;
            for(int i = 0;i < rowCount; i++){
                for(int j = 0; j < colCount; j++){
                    if(target == array[i][j]){
                        System.out.println("exist");
                        return true;
                    }
                }
            }
            System.out.println("not exist");
            return false;
    
        }
    }
    • resolution2:

      resolution2 主要借助了该数组的特点,每次从每行的最后一个数开始比较,如果target大于最后一个数,就跳转到下一行,如果小于就继续比较。

      /**
             * 运行时间:211ms
             占用内存:17904k
             * @param target
             * @param array
             * @return
             */
            public boolean Find(int target, int [][] array) {
                int rowCount = array.length;
                int colCount = array[0].length;
                int j = colCount - 1;//局部变量
                int i = 0;
    
                    while (j >= 0 && i < rowCount){//注意这里j能够取到0
                        if(target > array[i][j]){
                            i++;
                            j = colCount -1;//注意重新定义j的值
                            continue;
                        }else if(target < array[i][j]){
                            j--;
                        }else if(target == array[i][j]){
                            System.out.println("exist");
                            return true;
                        }
                }
                System.out.println("not exist");
                return false;
            }
    欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
  • 相关阅读:
    Rio手把手教学:如何打造容器化应用程序的一站式部署体验
    OCR技术浅探: 语言模型和综合评估(4)
    OCR技术浅探: 光学识别(3)
    OCR技术浅探 : 文字定位和文本切割(2)
    OCR技术浅探:特征提取(1)
    .NET加密方式解析--散列加密
    在Windows上搭建Git Server
    感知机
    企业级负载平衡概述
    Logistic Regression 模型
  • 原文地址:https://www.cnblogs.com/flyingcr/p/10326851.html
Copyright © 2011-2022 走看看