Java Streams在Codility上的性能为0%

vfh0ocws  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(93)

关于Codility的教训OddOccurrencesInArray
我使用以下代码获得了66%(性能0%):

public int solution(int[] A) {
    return Arrays
            .stream(A)
            .parallel()
            .boxed()
            .collect(Collectors.groupingBy(n -> n, Collectors.counting()))
            .entrySet()
            .parallelStream()
            .filter(entry -> entry.getValue() % 2 != 0)
            .findAny()
            .map(Map.Entry::getKey)
            .orElseThrow();
}

然而,我使用here的代码获得了100%的总成绩(性能100%):

public int solution(int[] A) {
    HashMap<Integer, Integer> histogram = new HashMap<>();
    for (int i = 0; i < A.length; i++) {
        if (histogram.containsKey(A[i])) {
            int occurrences = histogram.get(A[i]);
            occurrences++;
            histogram.put(A[i], occurrences);
        } else {
            histogram.put(A[i], 1);
        }
    }
    Set<Integer> keySet = histogram.keySet();
    for (int currentKey : keySet) {
        int occurrences = histogram.get(currentKey);
        if (occurrences % 2 != 0) return currentKey;
    }
    throw new RuntimeException();
}

以下混合解决方案的总得分为88%(1次性能测试失败):

public int solution(int[] A) {
    HashMap<Integer, Integer> histogram = new HashMap<>();
    for (int i = 0; i < A.length; i++) {
        if (histogram.containsKey(A[i])) {
            int occurrences = histogram.get(A[i]);
            occurrences++;
            histogram.put(A[i], occurrences);
        } else {
            histogram.put(A[i], 1);
        }
    }
    return histogram.entrySet()
            .parallelStream()
            .filter(n -> (n.getValue() % 2 != 0))
            .findAny()
            .map(Map.Entry::getKey)
            .orElseThrow();
}

我也试着把所有的parallelStream()都改成stream()。结果还是一样!
是流效率较低?还是只是Codility?

yb3bgrhw

yb3bgrhw1#

Codility修复了它,所有解决方案的总收益为100%(性能100%)

相关问题