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

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

    1.普通方法(不利用有序的特征)

     1 public class Solution {
     2     public boolean Find(int [][] array,int target) {
     3          
     4         for(int i=0; i<array.length; i++){
     5             for(int j=0; j<array[i].length; j++){
     6                 if(array[i][j] == target){
     7                     return true;
     8                 }
     9             }
    10         }
    11          
    12         return false;
    13     }
    14 }

    2.利用有序的特征,效率更高

     1 public class Main {
     2 
     3     public static void main(String[] args) {
     4 
     5         int[][] arrays = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 },
     6                 { 6, 8, 11, 15 } };
     7 
     8         int num = 5;
     9 
    10         Main main = new Main();
    11 
    12         System.out.println(main.find(arrays, num));
    13 
    14     }
    15 
    16     public Boolean find(int[][] arrays, int num) {
    17 
    18         Boolean result = false;
    19 
    20         if (null == arrays || 0 == arrays.length) {
    21             return result;
    22         }
    23 
    24         int rowLen = arrays.length;
    25         int colLen = arrays[0].length;
    26 
    27         for (int i = 0; i < rowLen; i++) {
    28             for (int j = colLen - 1; j >= 0; j--) {
    29 
    30                 if (arrays[i][j] == num) {
    31                     result = true;
    32                 } else if (arrays[i][j] > num) {
    33                     continue; // 左移一列
    34                 } else {
    35                     i++; // 下移一行
    36                     j++; // 下次循环,j会减1,为保证下次从同一列开始,这里先加1
    37                     if (i == rowLen || j == 0) {
    38                         return result;
    39                     }
    40                 }
    41 
    42             }
    43         }
    44         return result;
    45     }
    46 
    47 }
  • 相关阅读:
    mac配置ls命令显示不同文件不同颜色
    nginx安装
    PostgreSQL的架构
    /etc/sysctl.conf配置文件
    pg_hba.conf配置文件
    gitlab不支持mysql,这就是我学习PostgreSQL的原因
    postgresql安装
    git的三个区域比较
    mysql备份时的快照原理
    mysql密码管理
  • 原文地址:https://www.cnblogs.com/jiangyi-uestc/p/7954282.html
Copyright © 2011-2022 走看看