나의코드는 아래와 같다.
import java.util.*;
class Solution {
public int[] solution(int[] answers) {
int[] a= {1, 2, 3, 4, 5};
int[] b= {2, 1, 2, 3, 2, 4, 2, 5};
int[] c= {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
int[] count = new int[3];
for(int i =0; i<answers.length; i++){
if(answers[i] == a[i%a.length]){
count[0]++;
}
if(answers[i] == b[i%b.length]){
count[1]++;
}
if(answers[i] == c[i%c.length]){
count[2]++;
}
}
int max= Math.max(Math.max(count[0], count[1]),count[2]);
Queue<Integer> queue = new LinkedList<>();
for(int i=0; i<count.length; i++) {
if (count[i] == max) {
System.out.println(queue.offer(i+1));
}
}
int q= queue.size();
int[] answer = new int[queue.size()];
for(int i=0; i<q; i++){
answer[i] = queue.poll();
}
return answer;
}
}
마지막에 큐에 대한 사이즈에 따라서 for문을 loop를 돌게 했는데, 그 부분에서 실수가 발생해서 애를 먹었다.
반복문 탈출 조건에서 queue.size()는 queue를 poll() / offer()를 통해 사이즈에 변화를 주는경우 의도와 다르게 반복문을 돌 수 있다.
즉, 매 loop마다 for문의 조건을 확인하는데, i<queue.size()를 계속해서 호출하기때문에 queue.size가 시시각각 변화한다. 이 부분 유의하여야 할 필요성을 느꼈다.
다른 사람의 코드
import java.util.ArrayList;
class Solution {
public int[] solution(int[] answer) {
int[] a = {1, 2, 3, 4, 5};
int[] b = {2, 1, 2, 3, 2, 4, 2, 5};
int[] c = {3, 3, 1, 1, 2, 2, 4, 4, 5, 5};
int[] score = new int[3];
for(int i=0; i<answer.length; i++) {
if(answer[i] == a[i%a.length]) {score[0]++;}
if(answer[i] == b[i%b.length]) {score[1]++;}
if(answer[i] == c[i%c.length]) {score[2]++;}
}
int maxScore = Math.max(score[0], Math.max(score[1], score[2]));
ArrayList<Integer> list = new ArrayList<>();
if(maxScore == score[0]) {list.add(1);}
if(maxScore == score[1]) {list.add(2);}
if(maxScore == score[2]) {list.add(3);}
return list.stream().mapToInt(i->i.intValue()).toArray();
}
}
이 분의 경우도 같은 방식인데, 성능이 더 좋다.
필자의 경우, Queue를 이용하여서 최대값과 일치하는 값을 저장했다. 이는 ArrayList를 사용하는것과 비슷한다.
하지만 스트림을 이용한 부분에서 효율성이 차이가 난 것으로 보인다.
list.stream().mapToInt(i->i.intValue()).toArray();
list를 스트림으로 변환
int값으로 변환하여
배열로 변환
리턴.
반응형
'코딩테스트 > Java' 카테고리의 다른 글
[JAVA] 탐욕법(Greedy) "체육복" (0) | 2020.09.25 |
---|---|
[JAVA] 완전탐색 "소수 찾기" (0) | 2020.09.23 |
[JAVA] 정렬 "가장 큰 수" (0) | 2020.09.18 |
[JAVA] 힙 "이중우선순위큐" (0) | 2020.09.15 |
[JAVA] 힙 "디스크 컨트롤러" (0) | 2020.09.15 |