TIL(Today I Learned)
[TIL] 99클럽 코테 스터디 20일차 TIL + 프로그래머스 모의고사
zincah
2024. 11. 17. 00:01
반응형
문제 풀이
문제 탐색하기
이 문제는 답으로 주어진 배열을 1번 수포자가 찍는 규칙, 2번 수포자가 찍는 규칙, 3번 수포자가 찍는 규칙을 다 확인하면서 1,2,3번 수포자의 점수를 체크해야하는 완전 탐색 문제입니다.
각 수포자가 찍는 방식을 한 사이클이 끝날때까지를 배열로 선언하여 map에 key는 수포자의 번호, value는 점수를 저장합니다.
정답은 최고점을 가진 수포자를 출력하면 되는데 여기서 고려해야할 점은 같은 최고점을 가진 수포자를 오름차순으로 출력해야합니다. 따라서 map에 value로 저장된 점수 중 최고점을 구하고 최고점과 같은 점수를 가진 수포자를 따로 List에 저장합니다.
여기서 list를 배열로 변환하여 오름차순으로 정렬하게 되면 답을 구할 수 있습니다.
문제 풀이
import java.util.*;
class Solution {
static HashMap<Integer, Integer> map = new HashMap<>();
public int[] solution(int[] answers) {
map.put(1, 0);
map.put(2, 0);
map.put(3, 0);
for(int i=0; i<answers.length; i++){
oneScore(i, answers[i]);
twoScore(i, answers[i]);
threeScore(i, answers[i]);
}
int max = 0;
for(int i : map.keySet()){
max = Math.max(max, map.get(i));
}
List<Integer> list = new ArrayList<>();
for(int i : map.keySet()){
if(max == map.get(i)){
list.add(i);
}
}
int[] result = new int[list.size()];
for(int i=0; i<list.size(); i++){
result[i] = list.get(i);
}
Arrays.sort(result);
return result;
}
private static void oneScore(int i, int answer){
int[] oneResult = {1,2,3,4,5};
int idx = i%oneResult.length;
if(answer == oneResult[idx]){
map.put(1, map.get(1)+1);
}
}
private static void twoScore(int i, int answer){
int[] twoResult = {2,1,2,3,2,4,2,5};
int idx = i%twoResult.length;
if(answer == twoResult[idx]){
map.put(2, map.get(2)+1);
}
}
private static void threeScore(int i, int answer){
int[] threeResult = {3,3,1,1,2,2,4,4,5,5};
int idx = i%threeResult.length;
if(answer == threeResult[idx]){
map.put(3, map.get(3)+1);
}
}
}
오늘의 회고
마지막에 최고점을 가진 사람이 여러명일 경우 어떻게 출력해야 하는지... 이 부분에서 많이 헤맸던 것 같습니다ㅎㅎ 풀면서도 이렇게 푸는 것이 맞는지 고민하며 풀었는데ㅎㅎ 역시나 많은 문제를 풀어서 감을 익혀야할 것 같습니다!
반응형