import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* 从n个整数中查找出现频率最高的所有整数(用java实现)
* 示例:5,5,8,5,3,5,3,3,3,1
* 中出现频率最高的整数是3和5
* @author htcafe
*
*/
public class MyAnswer {
public static void main(String[] args) {
long start = System.currentTimeMillis();
int[] datas = getdata();
// int[] datas = {1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3};
Map<Integer, Integer> map = getMax(datas);
int count = getCount(map.values());
System.err.println(count);
display(map, count);
long end = System.currentTimeMillis();
System.err.println("Complete the check in " + (end - start) + " ms!" +
"\nThis test have " + datas.length + " datas!");
}
private static void display(Map<Integer, Integer> map, int count) {
for(Iterator<Integer> it = map.keySet().iterator(); it.hasNext();) {
int value = it.next();
if(count == map.get(value))
System.out.println(value);
}
}
private static int getCount(Collection<Integer> set) {
int temp = 0;
for(Iterator<Integer> it = set.iterator(); it.hasNext();) {
int value = it.next();
if(value > temp)
temp = value;
}
return temp;
}
private static Map<Integer, Integer> getMax(int[] datas) {
Map<Integer, Integer> temp = new HashMap<Integer, Integer>();
for(int i=0; i<datas.length; i++) {
Integer t = temp.get(datas[i]);
t = (t != null) ? t.intValue() : 0;
temp.put(datas[i], t + 1);
}
return temp;
}
private static int[] getdata() {
int NUMBER = 1000000;
int[] arr = new int[NUMBER];
Random ran = new Random(20090228);
int sign = -1;
for (int i = 0; i < NUMBER; i++) {
sign *= -1;
arr[i] = sign * ran.nextInt(NUMBER);
}
return arr;
}
}
从n个整数中查找出现频率最高的所有整数
最新推荐文章于 2021-09-18 15:40:43 发布