상세 컨텐츠

본문 제목

[Lesson 8] Leader - Dominator

Codility Lessons 풀이

by 발발개발 2025. 1. 17. 17:04

본문

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;
    }
}

관련글 더보기

댓글 영역