问题是给定一个数组,返回正整数数组中最常出现的元素。假设数组至少有一个元素。如果有多个模式,则返回最小的模式。
这是我的代码,但它不能传递这个数组 {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
最佳答案
我发现你的逻辑很不清晰和令人费解,所以我只是从头开始重写代码。我包括了一个 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));
}
}
关于java - 如何使用 hashmap 查找数组中的最小模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38363015/