查找出现次数最多的元素
例如:在数组 { 2, 3, 1, 2, 2, 5, 6, 8, 2, 3, 2, 4, 2 }中,元素2出现的次数最多,一共出现了 6次。3出现两次
分析
使用HashMap存储元素及其出现次数,然后添加进list中,对list排序。
import java.util.*;
public class Main{
public static void main(String[] args) {
int[] arr = { 2, 3, 1, 2, 2, 5, 6, 8, 2, 3, 2, 4, 2 };
int t = 4;
Map<Integer, Integer> map = new HashMap<>();
for (int i : arr)
map.merge(i, 1, Integer::sum);
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
list.sort((o1, o2) -> o1.getValue() == o2.getValue() ?
o1.getKey() - o2.getKey() :
o2.getValue() - o1.getValue());
for (int i = 0; i < t; i++)
System.out.println(list.get(i).getKey());
}
}
PS:本人水平有限,文中如有错漏,欢迎大家指出。转载请注明来源。
本文介绍了一种使用HashMap和List来找出数组中出现次数最多的元素的方法。通过存储元素及其出现次数,然后对这些数据进行排序,可以高效地找到最频繁出现的元素。
1459

被折叠的 条评论
为什么被折叠?



