[英]how to use hashmap to find smallest mode in the array
問題是給定一個數組返回正整數數組中最頻繁出現的元素。 假設數組中至少有一個元素。如果有多個模式,則返回最小模式。
這是我的代碼,但無法傳遞此數組{27,15,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));
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.