gpt4 book ai didi

java - 在二维数组中查找行的最大值和列的最小值

转载 作者:行者123 更新时间:2023-12-04 03:42:04 25 4
gpt4 key购买 nike

我需要编写一个 java 代码,将二维数组作为矩阵并检查每一行和每一列,并找到行中最大值但列中最小值的数字。

例如,13 是列的最小值和行的最大值:

the 13 is the min at col and max at the row

我写了代码,但我迷路了:

import java.util.Scanner;

public class maxmin {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("enter matrix size ");
int num = input.nextInt();
int num1 = input.nextInt();

maxMin(num, num1);
}

private static void maxMin(int num, int num1) {
int max = 0;
int min = 0;

int[][] matrix = new int[num][num1];
System.out.println("ENTER ARRAY NUMBERS");
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = input.nextInt();
}
}

for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
if (matrix[i][j] >= max) {
max = matrix[i][j];
for (int a = 0; a < matrix.length; a++) {
if (matrix[i][a] <= min) {
min = matrix[i][a];
}
if (max == min) {
System.out.println(max);
}
}
}
}
}
}
}

最佳答案

您可以使用 IntStream为此目的:

int[][] arr = {
{1, 2, 3, 6, 5},
{3, 2, 5, 6, 7},
{5, 6, 7, 8, 9},
{1, 3, 0, 2, 4}};
int num = Arrays
// iterate over the nested arrays,
// i.e. rows of the 2d array
.stream(arr)
// find maximum value of the row
// return IntStream of maximums
.mapToInt(row -> Arrays.stream(row)
// maximum value of the row
.max().orElse(Integer.MIN_VALUE))
// find minimum value of row maximums
.min().orElse(Integer.MIN_VALUE);
// output
System.out.println(num); // 4

关于java - 在二维数组中查找行的最大值和列的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65848223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com