https://app.codility.com/programmers/lessons/8-leader/dominator/
Dominator coding task - Learn to Code - Codility
Find an index of an array such that its value occurs at more than half of indices in the array.
app.codility.com
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
class Solution {
public int solution(int[] A) {
Map<Integer, Integer> cntMap = new HashMap<>();
for (int input : A) {
if (cntMap.containsKey(input)) {
cntMap.replace(input, cntMap.get(input) + 1);
} else {
cntMap.put(input, 1);
}
}
Optional<Integer> dominator = cntMap.entrySet()
.stream()
.filter(o -> o.getValue() > A.length / 2)
.map(Map.Entry::getKey)
.findAny();
int result = -1;
if (dominator.isPresent()) {
for (int i = 0; i < A.length; i++) {
if (A[i] == dominator.get()) {
result = i;
break;
}
}
}
return result;
}
}
[Lesson 9] Maximum slice problem - MaxProfit (0) | 2025.01.20 |
---|---|
[Lesson 8] Leader - EquiLeader (1) | 2025.01.20 |
[Lesson 7] Stacks and Queues - Fish (0) | 2025.01.17 |
[Lesson 7] Stacks and Queues - StoneWall (0) | 2025.01.17 |
[Lesson 7] Stacks and Queues - Nesting (1) | 2025.01.16 |
댓글 영역