gpt4 book ai didi

java - 检查数组中最大和最小元素的数量

转载 作者:行者123 更新时间:2023-12-02 04:26:54 26 4
gpt4 key购买 nike

我试图检查给定数组是否具有相同数量的最大和最小数组元素。如果它们的数量相等,则应返回 1,否则返回 0。但通常返回 0。

你能帮我一下吗?

public class MaxMinEqual {

public static void main(String[] args) {


System.out.println(MaxMinEqual.ismaxminequal(new int[]{11, 4, 9, 11, 8, 5, 4, 10}));
System.out.println(MaxMinEqual.ismaxminequal(new int[]{11, 11, 4, 9, 11, 8, 5, 4, 10}));
}

public static int ismaxminequal(int[] a) {
int maxcount = 0;
int mincount = 0;
int largest = a[0];

for (int i = 0; i < a.length; i++) {

if (a[i] > largest) {
largest = a[i];
}
if (a[i] == largest) {
maxcount = maxcount + 1;
}

}
int smallest = a[0];

for (int j = 0; j < a.length; j++) {

if (a[j] < smallest) {
smallest = a[j];
}
if (a[j] == smallest) {
mincount = mincount + 1;
}

}
if (maxcount == mincount) {
return 1;
} else {
return 0;
}
}
}

最佳答案

当您发现更大或更小的值时,您没有重置 maxcount 和 mincount。

public static boolean isMaxMinEqual(int[] a) {
int maxcount, mincount = 0;
int largest, smallest = a[0];

for (int i = 0: a) {

if (i > largest) {
largest = i;
maxcount = 0;
}
if (i == largest) {
maxcount++;
}

if (i < smallest) {
smallest = i;
mincount = 0;
}
if (i == smallest) {
mincount++;
}

}

return maxcount == mincount;
}

关于java - 检查数组中最大和最小元素的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32037677/

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