Java 在二维数组中查找最大和最小数的索引
我真的很难找到5x5数组中最大和最小数字的索引,其中生成了多达1000个随机数。这是我的代码:Java 在二维数组中查找最大和最小数的索引,java,arrays,algorithm,max,min,Java,Arrays,Algorithm,Max,Min,我真的很难找到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.
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 + " ");
}
}
import java.util.Random;
公共类MaxMinArray{
公共静态void main(字符串参数[]){
int x=0,y=0,max=0,min=1000;;
int[][]数字=新int[5][5];
对于(x=0;x您应该跟踪最大/最小元素的x
和y
索引。无需后期处理,只需记账即可:
if(max < numbers[x][y]) {
max = numbers[x][y];
maxX = x;
maxY = y;
}
if(最大值<数字[x][y]){
最大值=数字[x][y];
maxX=x;
maxY=y;
}
使用点
跟踪索引
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.");
}
最小点=新点(0,0);
最大点=新点(0,0);
对于(int[]行:数字){
for(int col=0;col数字[max.X][max.Y])
{max.X=行;max.Y=列;}
}
}
如果(number.length>0){
System.out.println(数字[min.X][min.Y]+“是最小值”);
System.out.println(数字[max.X][max.Y]+“是最大值”);
}
对于如此小的规模,简单的双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;
}
}
}
int n=5;
int min=数组[0][0];
int[]minIndex={0,0};
int max=数组[0][0];
int[]maxIndex={0,0};
对于(int i=0;i二维数组中的单个索引意味着什么?您应该同时存储x
和y
。在跟踪max/min的if
块中这样做最有意义。仅供参考:您发布的代码不会编译。