【发布时间】:2016-11-16 17:03:04
【问题描述】:
问题是,给定一个数组会返回一个正整数数组中出现频率最高的元素。假设数组至少有一个元素。如果有多个模式返回最小的模式。
这是我的代码,但它不能传递这个数组 {27, 15, 15, 11, 27}。
另外,如何在 for-each 循环中不使用i 来修改我的代码?
public int mode(int input[]){
if(input.length==1)
return input[0];
Map<Integer,Integer> mymap = new HashMap<Integer,Integer>();
int count=0;
for(int i = 0 ;i < input.length;i++){
count = mymap.containsKey(input[i]) ? mymap.get(input[i]) : 0;
mymap.put(input[i],count+1);
}
int firstmode = -1;
int secondmode = -1;
int i=0;
for(int k :mymap.keySet()){
if(mymap.get(k)>secondmode){
i++;
firstmode=k;
if(i%2==0){ //if there more than one mode,then compare them
if(firstmode>k){
firstmode=k;
i--;
}
}
secondmode=mymap.get(k);
}
}
return firstmode;
}
更新的测试用例
{1, 1, 2, 3} should return 1
{1, 1, 2, 3, 3} should return 1
{27, 15, 15, 11, 27} should return 15
{27, 15, 15, 11, 27, 27} should return 27
{1, 1, 6, 6, 6, 3, 3, 3} should return 3
{27, 15, 15, 27, 11, 11, 11, 14, 15, 15, 16, 19, 99, 100, 0, 27}
should return 15
{42} should return 42
【问题讨论】:
-
问题:mode 是什么意思?您是指最频繁出现的最小值吗?您能否提供几个示例数组,其中您的代码可以正常工作,并且上述数组的输出不正确?
-
@alwaysANewbie 。众数是一组数据中出现频率最高的值。
-
Stream.of(input).collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting())).firstKey()
-
是的,但是找到“最小模式”是什么意思?假设您有出现
4次的数字3,然后出现5次的数字4。哪个是最小的?你可能会说3,因为它小于4,但3只出现4次,而4出现5次。这个问题模棱两可。
标签: java arrays algorithm dictionary