
8-1. Dominator
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
class Solution { public int solution(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].
배열 A가 N개의 정수로 구성되어 있습니다. 배열 A의 지배자는 A의 요소의 절반 이상에서 발생하는 값입니다.
예를 들어, 배열 A가 다음과 같다고 가정합니다:
A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 배열 A의 지배자는 3입니다. 왜냐하면 3은 A의 8개의 요소 중 5개 요소(즉, 인덱스 0, 2, 4, 6, 7에서)에서 발생하며, 5는 8의 절반 이상이기 때문입니다.
다음과 같은 함수를 작성하세요:
class Solution {
public int solution(int[] A);
}
이 함수는 N개의 정수로 구성된 배열 A가 주어졌을 때, 배열 A의 지배자가 발생하는 요소의 인덱스를 반환합니다. 배열 A에 지배자가 없는 경우 함수는 -1을 반환해야 합니다.
예를 들어, 배열 A가 다음과 같다고 가정합니다:
A[0] = 3 A[1] = 4 A[2] = 3 A[3] = 2 A[4] = 3 A[5] = -1 A[6] = 3 A[7] = 3 함수는 0, 2, 4, 6 또는 7을 반환할 수 있습니다.
다음 가정을 위한 효율적인 알고리즘을 작성하세요:
N은 [0…100,000] 범위 내의 정수입니다.
배열 A의 각 요소는 [−2,147,483,648…2,147,483,647] 범위 내의 정수입니다.
문제풀이
import java.util.*;
class Solution {
public int solution(int[] A) {
if (A.length == 0) return -1;
Map<Integer, Integer> countMap = new HashMap<>();
int dominator = A[0];
int maxCount = 0;
for (int num : A) {
countMap.put(num, countMap.getOrDefault(num, 0) + 1);
if (countMap.get(num) > maxCount) {
maxCount = countMap.get(num);
dominator = num;
}
}
if (maxCount <= A.length / 2) return -1;
for (int i = 0; i < A.length; i++) {
if (A[i] == dominator) return i;
}
return -1;
}
}
해시맵을 사용하여 동일항목을 체크하고 그 수를 저장하여 문제를 풀이
제출결과

문제풀어보기 -> https://app.codility.com/programmers/lessons/8-leader/dominator/