问题是给定一个数组返回正整数数组中最常出现的元素。假设数组至少有一个元素。如果有多个模式返回最小模式。
这是我的代码,但它无法传递此数组{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
答案 0 :(得分:1)
我发现你的逻辑很不清楚和复杂,所以我只是从头开始重写代码。我在Java 8之前包含了一个解决方案,在Java 8之后包含了另一个解决方案。
import java.util.HashMap;
import java.util.Map;
import java.util.IntStream;
import static java.util.Comparator.naturalOrder;
public class Solution {
public static int smallestMode(int input[]) {
Map<Integer, Integer> counters = new HashMap<>();
for (Integer i : input) {
Integer counter = counters.get(i);
counters.put(i, counter == null ? 1 : counter + 1);
}
int mode = Integer.MIN_VALUE;
for (int counter : counters.values()) mode = Math.max(mode, counter);
int result = Integer.MAX_VALUE;
for (Map.Entry<Integer, Integer> entry : counters.entrySet()) {
if (entry.getValue() == mode) result = Math.min(result, entry.getKey());
}
return result;
}
public static int smallestModeJava8(int input[]) {
Map<Integer, Long> counters = IntStream.of(input).boxed().collect(groupingBy(identity(), counting()));
long mode = counters.values().stream().max(naturalOrder()).get();
return counters.entrySet().stream().filter(entry -> entry.getValue() == mode).map(Map.Entry::getKey).min(naturalOrder()).get();
}
public static void main(String[] args) {
int[] input = {27, 15, 15, 11, 27};
System.out.println(smallestMode(input));
System.out.println(smallestModeJava8(input));
}
}