gpt4 book ai didi

java - 如何找到数组中重复次数最多的数字?

转载 作者:行者123 更新时间:2023-11-29 05:14:09 26 4
gpt4 key购买 nike

我知道有类似的问题。但这是一个技巧。假设我们有这个数组:

int[] list = {1, 2, 3, 1, 0, 0, 0, 5, 6, 1569, 1, 2, 3, 2, 1569, 3};

System.out.println("Most repeated value is: " + ???);

/* Now As you can see 0's, 1's, 2's and 3's has the same frequency "3 times". In this case,
I need to print the smallest number which is the most frequently repeated. So that,
prompt should be 0 */

为了更容易理解:

// All the digits except 5 and 6 and 1569's rest of the values repeated 3 times. I have to
// print the smallest number which occurs most.

如果您能用 Java 向我展示一个明智的解决方案代码,我将不胜感激。感谢检查。

最佳答案

    public static void main(String args[]) {
int[] list = {1, 2, 3, 1, 0, 0, 0, 5, 6, 1569, 1, 2, 3, 2, 1569, 3};

Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for (Integer nextInt : list) {
Integer count = map.get(nextInt);
if (count == null) {
count = 1;
} else {
count = count + 1;
}
map.put(nextInt, count);
}

Integer mostRepeatedNumber = null;
Integer mostRepeatedCount = null;
Set<Integer>keys = map.keySet();
for (Integer key : keys) {
Integer count = map.get(key);
if (mostRepeatedNumber == null) {
mostRepeatedNumber = key;
mostRepeatedCount = count;
} else if (count > mostRepeatedCount) {
mostRepeatedNumber = key;
mostRepeatedCount = count;
} else if (count == mostRepeatedCount && key < mostRepeatedNumber) {
mostRepeatedNumber = key;
mostRepeatedCount = count;
}
}

System.out.println("Most repeated value is: " + mostRepeatedNumber);

}

将给出以下输出...

Most repeated value is: 0

关于java - 如何找到数组中重复次数最多的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27197917/

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