Regarding Codility's lesson OddOccurrencesInArray
I got total of 66% (Performance 0%) using the following code:
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();
}
However, I got total of 100% (Performance 100%) using code from here:
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();
}
The following hybrid solution got total of 88% (1 Performace test failed):
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();
}
I also tried to change all parallelStream()
to stream()
. Same results!
Are streams less efficient? or it's just Codility?
Codility fixed it, and all solutions are getting total of 100% (Performance 100%)