본문 바로가기
코딩 테스트

[Codility] Lesson8. Dominator

by zoodi 2021. 3. 3.
728x90

🔮문제

An array A consisting of N integers is given. The dominator of array A is the value that occurs in more than half of the elements of A.

For example, consider array A such that

A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3

The dominator of A is 3 because it occurs in 5 out of 8 elements of A (namely in those with indices 0, 2, 4, 6 and 7) and 5 is more than a half of 8.

Write a function

int solution(vector<int> &A);

that, given an array A consisting of N integers, returns index of any element of array A in which the dominator of A occurs. The function should return −1 if array A does not have a dominator.

For example, given array A such that

A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3

the function may return 0, 2, 4, 6 or 7, as explained above.

Write an efficient algorithm for the following assumptions:

  • N is an integer within the range [0..100,000];
  • each element of array A is an integer within the range [−2,147,483,648..2,147,483,647].

🔮풀이

map 자료구조로 가장 큰 빈도의 dominator를 구한 후 dominator 의 첫번째 index를 반환

  • N의 길이 100,000 이하 => O(N) 이하의 시간복잡도로 해결해야 함
  • A 원소 값의 범위 => int 자료형으로 해결 가능

🔮코드

 #include <algorithm>
 #include <map>
 #include <vector>
 #include <iostream>

int solution(vector<int> &A) {
    int size = A.size();
    int dominator = -1; int _max = -1;
    int half = size/2;
    int answer = 0;

    map<int, int> m;
    for(int i=0; i<size; i++){
        m[A[i]]++;
    }

    //dominator 값 설정
    for(auto x: m){
        if(x.second > half){
            if(x.second > _max){
                _max = x.second;
                dominator = x.first;
            }
        }
    }
    //dominator가 없는 경우 -1 반환
    if(dominator == -1){
        return -1;
    }
    //dominator의 index 반환
    for(int i=0; i<size; i++){
        if(A[i] == dominator){
            answer = i;
            break;
        }
    }
    return answer;
}
728x90

댓글