gpt4 book ai didi

java - 如何在Java中的短路数组中找到最少和最多出现的数字

转载 作者:行者123 更新时间:2023-11-30 06:46:47 25 4
gpt4 key购买 nike

你能帮我解决这段代码吗,它找到了出现次数最多的值,但我不知道如何才能找到最少的值。

      int arr[] = new int[] { 2, 3, 5, 4, 5, 4, 4, 2, 4, 3, 5, 4, 2, 4, 2, 4, 2, 2, 18 };
System.out.println("Most Occurs : " + findElementThatOccursMostly(arr));
System.out.println("Fewest Occurs : " + findElementThatOccursMin(arr));
// a shorting array that finds the most occurs value which is 4
// but can't find the fewest occur number which is 18(only once)
}

int findElementThatOccursMostly(int arr[]) {
int tempOccurrences = 0;
int tempElement = 0;
int mostOccurrences = 0;
int mostElement = 0;
for (int i = 0; i < arr.length; i++) {
if (tempElement == arr[i]) {
tempOccurrences++;
if (tempOccurrences > mostOccurrences) {
mostOccurrences = tempOccurrences;
mostElement = tempElement;
}
} else {
tempOccurrences = 1;
tempElement = arr[i];
}
}
return mostElement;
}

最佳答案

无论如何我都找不到用上面的代码解决你的问题所以,这是我的想法,用另一种方法来完成这两个:

public static void main(String[] args) {
List<Integer> list = Arrays.asList(2, 3, 5, 4, 5, 4, 4, 2, 4, 3, 5, 4, 2, 4, 2, 4, 2, 2, 18);
System.out.println(mostCommon(list));
System.out.println(lessCommon(list));
}

public static <T> T mostCommon(List<T> list) {
Map<T, Integer> map = new HashMap<>();

for (T t : list) {
Integer val = map.get(t);
map.put(t, val == null ? 1 : val + 1);
}

Map.Entry<T, Integer> max = null;

for (Map.Entry<T, Integer> e : map.entrySet()) {
if (max == null || e.getValue() > max.getValue())
max = e;
}

return max.getKey();
}

public static <T> T lessCommon(List<T> list) {
Map<T, Integer> map = new HashMap<>();

for (T t : list) {
Integer val = map.get(t);
map.put(t, val == null ? 1 : val + 1);
}

Map.Entry<T, Integer> max = null;

for (Map.Entry<T, Integer> e : map.entrySet()) {
if (max == null || e.getValue() < max.getValue())
max = e;
}

return max.getKey();
}

关于java - 如何在Java中的短路数组中找到最少和最多出现的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47083383/

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