package codility;
import java.util.Arrays;
import java.util.Collections;
public class EquiLeader_221229 {
public static void main(String[] args) {
int [] A = {4,3,4,4,4,2};
System.out.println(solution(A));
}
public static int solution(int[] A) {
int answer = 0;
Integer [] A_top = Arrays.stream(Arrays.copyOfRange(A, 0, A.length/2)).boxed().toArray(Integer[]::new);
Integer [] A_bottom = Arrays.stream(Arrays.copyOfRange(A, A.length/2, A.length)).boxed().toArray(Integer[]::new);
Arrays.sort(A_top);
Arrays.sort(A_bottom);
int at, ab;
if(A_top[A_top.length-1] == A_bottom[A_bottom.length-1]){
at = Collections.frequency(Arrays.asList(A_top), A_top[A_top.length-1]);
ab = Collections.frequency(Arrays.asList(A_bottom), A_bottom[A_bottom.length-1]);
answer = Math.min(at,ab);
}
return answer;
}
}
1차 제출안!
번역기가 초월번역을 해주었다!
답 돌려보니 Max 값이 아니라 빈도수 카운트였음!
그렇다면 다시...
(틀린 것 좀 확인하게 예제가 좀 많았으면 좋겠군요...)
어쨌든 빈도수면 반 안 자르고 이렇게 풀면 됨 ↓
(배열은 count 필요한 것만 모아 봤음...)
package codility;
import java.util.HashMap;
import java.util.Map;
public class EquiLeader_221229 {
public static void main(String[] args) {
int [] A = {4,3,4,4,4,2};
System.out.println(solution(A));
}
public static int solution(int[] A) {
int answer = 0;
int leader = 0;
int temp = 0;
int [] counter = {0, 0, 0, 0, 0};
//map 키값용 , map 최대값용, 리더 확인용 카운터, 반 자르기용 카운터, 최대값용
if(A.length == 0){
answer = 0;
return answer;
}
Map <Integer, Integer> map = new HashMap<>();
for(int i : A){
map.put(i, map.getOrDefault(i, 0)+1);
}
counter[1] = 1; //초기값 설정
for(int i : map.keySet()){
counter[0] = map.get(i);
if(counter[0] > counter[1]){
counter[1] = counter[0];
counter[4] = i;
}
}
if(counter[1] > A.length/2){
leader = counter[4];
counter[2] = counter[1];
}else{
answer = 0;
return 0;
}
for(int i=0; i<A.length; i++){
if(A[i] == leader){
counter[3] = counter[3] + 1;
}
if( counter[3] > (i+1)/2 ){
temp = counter[2] - counter[3];
if( temp > (A.length -i -1)/2 ){
answer++;
}
}
}
return answer;
}
}
댓글
댓글 쓰기