-
[프로그래머스] 모의고사 자바 완전순회코딩테스트 2025. 4. 6. 11:03반응형
https://school.programmers.co.kr/learn/courses/30/lessons/42840
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
문제
세 사람은 각각 다음과 같은 방식으로 문제를 찍는다.
1번 찍는 방식: 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, ...
2번 찍는 방식: 2, 1, 2, 3, 2, 4, 2, 5, 2, 1, 2, 3, 2, 4, 2, 5, ...
3번 찍는 방식: 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, 3, 3, 1, 1, 2, 2, 4, 4, 5, 5, ...주어진 정답배열 answers와 세 사람의 답안을 비교해 가장 많은 정답을 맞춘 사람을 오름차순으로 정렬해 구하시오.
접근
1.1,2,3번의 정답방식을 배열로 담는다.
2. 번호 순대로 각각 맵에 담는다.
3. while문으로 순서대로 정답과 각 사람을 비교한다.
4. 비교 결과를 반환한다.public int[] solution(int[] answers) { int[] one = new int[]{1, 2, 3, 4, 5}; int[] two = new int[]{2, 1, 2, 3, 2, 4, 2, 5}; int[] three = new int[]{3, 3, 1, 1, 2, 2, 4, 4, 5, 5}; Map<Integer, int[]> m = new HashMap<>(); m.put(1, one); m.put(2, two); m.put(3, three); int totalLen = answers.length; int[] counts = new int[4]; int target = 1; while(target <= 3){ int idx = 0; while(idx < totalLen){ int[] compare = m.get(target); int cIdx = idx; if(idx % compare.length == 0){ cIdx = cIdx % compare.length; } if(answers[idx] == compare[cIdx]) counts[target] ++; idx ++; } target ++; } int maxCount = Arrays.stream(counts).max().orElse(0); return IntStream.range(1, counts.length).filter(i -> counts[i] == maxCount).boxed().sorted().mapToInt(Integer::intValue).toArray(); }
발견된 문제
1.cIdx를 구하는 과정에서 런타임에러가 발생할 수 있음
2. 불필요한 if(idx % compare.length == 0){ 연산수정
1. 채점과정 효율화
맵에 넣고 다시 빼는 과정 없이 정의한 배열 자체를 이용해 바로 counts에 집계
2. 최고점수 판별 수정
Arrays.stream 대신 Math.max로 간략화public int[] solution2(int[] answers){ int[] one = new int[]{1, 2, 3, 4, 5}; int[] two = new int[]{2, 1, 2, 3, 2, 4, 2, 5}; int[] three = new int[]{3, 3, 1, 1, 2, 2, 4, 4, 5, 5}; int[] counts = new int[4]; for(int i = 0; i < answers.length; i ++){ if(answers[i] == one[i % one.length]){ counts[1] ++; } if(answers[i] == two[i % two.length]){ counts[2] ++; } if(answers[i] == three[i % three.length]){ counts[3] ++; } } int maxCount = Math.max(counts[1], Math.max(counts[2], counts[3])); return IntStream.range(1, 4).filter(i -> counts[i] == maxCount).sorted().toArray(); }
반응형'코딩테스트' 카테고리의 다른 글
[프로그래머스] 완주하지 못한 선수 자바 해시 맵 활용 (0) 2025.04.06 [프로그래머스] k번째 수 자바 정렬 (0) 2025.04.06 [프로그래머스] 체육복 자바 (0) 2025.04.06 [프로그래머스] 실패율 자바 리스트 정렬, 객체 (0) 2025.04.05 [프로그래머스] 크레인 인형뽑기 게임 자바 Stack (0) 2025.04.05