我必须找到双精度数组中出现次数最多的元素。我是这样做的:
int max = 0;
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if (array[i]==array[j])
count++;
}
if (count >= max)
max = count;
}
这个程序可以工作,但是太慢了!我必须找到一个更好的解决方案,有人能帮我吗?
发布于 2012-11-26 00:42:17
使用Collections.frequency
选项:
List<String> list = Arrays.asList("1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8");
int max = 0;
int curr = 0;
String currKey = null;
Set<String> unique = new HashSet<String>(list);
for (String key : unique) {
curr = Collections.frequency(list, key);
if(max < curr){
max = curr;
currKey = key;
}
}
System.out.println("The number " + currKey + " happens " + max + " times");
输出:
The number 12 happens 10 times
发布于 2020-05-07 20:29:37
使用Java 8的解决方案
int result = Arrays.stream(array)
.boxed()
.collect(Collectors.groupingBy(i->i,Collectors.counting()))
.values()
.stream()
.max(Comparator.comparingLong(i->i))
.orElseThrow(RuntimeException::new));
发布于 2012-11-26 00:43:49
我将建议另一种方法。我不知道这样做会不会更快。
对数组进行快速排序。使用内置的Arrays.sort()方法。
现在比较相邻的元素。考虑这个例子:
1 1 1 4 4 4 9 9 9 10 10 29 29 29
当相邻元素不相等时,您可以停止计算该元素。
https://stackoverflow.com/questions/13553009
复制相似问题