【问题标题】:finding the index of largest and smallest numbers in a 2D Array查找二维数组中最大和最小数字的索引
【发布时间】:2014-03-05 10:12:17
【问题描述】:

我真的很难找到 5x5 数组的最大和最小数字的索引,其中生成的随机数高达 1000。这是我的代码:

import java.util.Random;

public class MaxMinArray {

    public static void main (String args[]) {

    int x=0, y=0, max=0, min=1000;;
    int[][] numbers = new int[5][5];

    for (x=0; x<numbers.length; x++) {                  //outer for          
        for(y=0; y<numbers.length; y++) {               //inner for    
            numbers[x][y]= (int)(Math.random()*1000);   //random generator

            if(max < numbers[x][y])                     //max number
                max = numbers[x][y];

            if(min>numbers[x][y])                       //min number
                min = numbers[x][y];

            int maxIndex = 0;

            for(int index = 1; index<numbers.length; index++)
                if(numbers[maxIndex]< numbers[index])
                    maxIndex = index;
            }
        }
        System.out.println("Max number in array:" + max + " ");
        System.out.println("Max number is in" + maxIndex + " ");
        System.out.println("Min number in array:" + min + " ");
    }
}

【问题讨论】:

  • 二维数组中的单个索引是什么意思?您应该同时存储xy。在您跟踪最大/最小值的同一 if 块中执行此操作是最有意义的。
  • 仅供参考:您发布的代码无法编译。

标签: java arrays algorithm max min


【解决方案1】:

您应该跟踪最大/最小元素的xy 索引。无需后期处理,只需要记账即可:

if(max < numbers[x][y]) {
    max = numbers[x][y];
    maxX = x;
    maxY = y;
}

【讨论】:

    【解决方案2】:

    使用Point 来跟踪您的索引。

    Point min = new Point(0, 0); 
    Point max = new Point(0, 0);
    
    for(int[] row: numbers) {
        for(int col= 0; col < row.length; col++) {
            if(numbers[row][col] < numbers[min.X][min.Y])
                {max.X = row; min.Y = col;}
            if(numbers[row][col] > numbers[max.X][max.Y])
                {max.X = row; max.Y = col;}
        } 
    }
    
    if(numbers.length > 0) {
        System.out.println(numbers[min.X][min.Y] + " is the minimum.");
        System.out.println(numbers[max.X][max.Y] + " is the maximum."); 
    }
    

    【讨论】:

      【解决方案3】:

      对于这么小规模的东西,一个简单的双 for 循环应该是最容易理解和利用的。

      int n=5;
      int min = array[0][0]; 
      int[] minIndex = {0,0};
      int max = array[0][0];
      int[] maxIndex = {0,0};
      
      for (int i=0; i<n; i++) 
      {
      for (int j=0; j<n; j++) 
      {
      if (array[i][j] < min) 
      { 
      min = array[i][j];
      minIndex[0] = i;
      minIndex[1] = j;
      }
      if (array[i][j] > max) { 
      max = array[i][j];
      maxIndex[0] = i;
      maxIndex[1] = j;
      }
      }
      }
      

      对于非平凡的维度,这可能是一种缓慢的方法,但对于这种大小的矩阵,n^2 复杂度很好。

      编辑:哇,我错过了关于索引的部分。

      【讨论】:

        猜你喜欢
        • 2015-10-11
        • 1970-01-01
        • 2019-03-31
        • 1970-01-01
        • 2015-04-06
        • 2014-06-12
        • 1970-01-01
        • 2016-03-11
        • 2022-01-12
        相关资源
        最近更新 更多