https://app.codility.com/demo/results/training5G789P-4S7/
A non-empty array A consisting of N integers is given.
The leader of this array is the value that occurs in more than half of the elements of A.
An equi leader is an index S such that 0 ≤ S < N − 1 and two sequences A[0], A[1], ..., A[S] and A[S + 1], A[S + 2], ..., A[N − 1] have leaders of the same value.
For example, given array A such that:
A[0] = 4
A[1] = 3
A[2] = 4
A[3] = 4
A[4] = 4
A[5] = 2
we can find two equi leaders:
0, because sequences: (4) and (3, 4, 4, 4, 2) have the same leader, whose value is 4.
2, because sequences: (4, 3, 4) and (4, 4, 2) have the same leader, whose value is 4.
The goal is to count the number of equi leaders.
Write a function:
class Solution { public int solution(int[] A); }
that, given a non-empty array A consisting of N integers, returns the number of equi leaders.
For example, given:
A[0] = 4
A[1] = 3
A[2] = 4
A[3] = 4
A[4] = 4
A[5] = 2
the function should return 2, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [−1,000,000,000..1,000,000,000].
Copyright 2009–2023 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
// you can also use imports, for example:
// import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
import java.util.*;
class Solution {
public int solution(int[] A) {
//리더찾기
int[] copyA = new int[A.length];
copyA = A.clone();
Arrays.sort(copyA);
int leader = 0;
int tmpLeader = copyA[A.length/2];
int cntLeader = 0;
for(int i=0; i<copyA.length; i++){
if(copyA[i] == tmpLeader){
cntLeader ++;
}
}
if(cntLeader>=A.length/2){
leader = tmpLeader;
}
else{
return 0;
}
int left = 0;
int right = A.length;
int leftLeaderCnt = 0;
int rightLeaderCnt = cntLeader;
int answer = 0;
for(int current : A){
left ++;
right --;
if(current == leader){
rightLeaderCnt --;
leftLeaderCnt ++;
}
if(rightLeaderCnt > right/2 && leftLeaderCnt > left/2){
answer ++;
}
}
return answer;
}
}
효율성 문제를 해결하기 위해서, 우선 리더를 구한다.
이 후, 배열의 왼쪽에서 오른쪽으로 이동하면서
왼쪽 배열의 수와 오른쪽 배열의 수를 세고
리더일 경우 왼쪽 리더 카운트는 증가시키고 오른쪽 리더 카운트는 감소시킨다.
마지막 if문에서 각 구간에서 리더가 맞는지 확인하고
둘다 리더일 경우 answer 증가시켜서 리턴한다.