簡體   English   中英

查找2D數組中最大和最小數字的索引

[英]finding the index of largest and smallest numbers in a 2D Array

我真的很難找到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(max < numbers[x][y]) {
    max = numbers[x][y];
    maxX = x;
    maxY = y;
}

使用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."); 
}

對於這種小規模的東西,簡單的雙循環應該是最容易理解和利用的。

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復雜度很好。

編輯:哇,我錯過了關於指數的部分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM