java—返回最常出现的模式的方法

2cmtqfgy  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(252)

我需要帮助解决这个问题:
编写接受测试等级数组(0–100)的方法模式,并返回模式,即出现频率最高的等级。如果有多种模式,则返回最小的模式。
我的代码不工作:请帮助,谢谢!

public static int mode(int[] marks) {
    int count = 0;
    int count0 = 0;
    int mostFrequent = marks[0];
    for (int x = 0; x < marks.length; x++) {
        if (marks[x] == mostFrequent) {
            count++;
        }
    }
    if (count>count0) {
       count0  = count;
       mostFrequent = marks[count];
    }
    return mostFrequent;
}

例如:
如果marks={1,2,4,6,1,1,1},它就工作了
如果marks={1,2,4,1,3,2,3,5,5},则不起作用

disho6za

disho6za1#

你需要计算所有数字的出现次数。请尝试以下操作。

public static int mode(int[] marks) {
    Map<Integer, Integer> myMap = new HashMap<>();
    IntStream.of(marks).forEach(x -> myMap.merge(x, 1, Integer::sum)); // Take the occurences of each number
    Integer maxOccurence = Collections.max(myMap.values()); // Take the maximum
    return myMap.entrySet().stream().filter(entry -> entry.getValue() == maxOccurence).findFirst().get().getKey(); // Take the first(smallest) key which matches the maximum
}
cxfofazt

cxfofazt2#

这应该可以做到:

public static int mode(int[] marks) {
        return Arrays.stream(marks)
                .boxed()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .sorted(Comparator.comparing(Map.Entry<Integer, Long>::getValue).reversed().thenComparing(Map.Entry<Integer, Long>::getKey))
                .findFirst()
                .map(Map.Entry::getKey).orElse(0);
    }

注意:如果传递的数组为空,则最后一行将0设置为默认值。

.map(Map.Entry::getKey).orElse(0);

如果要在这种情况下引发异常,请将其更改为:

.map(Map.Entry::getKey).orElseThrow(RuntimeException::new);

相关问题