코딩테스트 풀이/JAVA
[프로그래머스/Lv.0] 등수 매기기
무지맘
2023. 5. 30. 12:46
1. Input, Output, Example
- 학생들의 영어 점수와 수학 점수를 차례대로 담은 배열이 주어졌을 때, 영어 점수와 수학 점수의 평균을 기준으로 매긴 등수를 담은 배열을 반환
2. Constraint
1) 0 ≤ score[0], score[1] ≤ 100
2) 1 ≤ score의 길이 ≤ 10
3) score의 원소 길이는 2이다.
4) score는 중복된 원소를 갖지 않는다.
3. Code
1) 첫 코드(2023/05/30)
import java.util.*;
class Solution {
public int[] solution(int[][] score) {
int[] ans = new int[score.length];
float[] avg = new float[score.length];
HashMap<Float,Integer> m = new HashMap<>();
for(int i=0 ; i<score.length ; i++){
avg[i] = (score[i][0]+score[i][1])/2.0f;
m.put(avg[i], m.getOrDefault(avg[i],0)+1);
}
List<Float> list = new ArrayList<>(m.keySet());
list.sort(Comparator.naturalOrder());
int rank = 1;
for(int j=list.size()-1 ; j>=0 ; j--){
int count = 0; float max = list.get(j);
for(int i=0 ; i<avg.length && count<=m.get(max) ; i++)
if(avg[i]==max){
ans[i] = rank;
count++;
}
rank += m.get(max);
}
return ans;
}
}
2) 다른 사람의 풀이를 보던 중 가장 마음에 들었던 것(2023/05/30)
import java.util.*;
class Solution {
public int[] solution(int[][] score) {
List<Integer> scoreList = new ArrayList<>();
for(int[] t : score){
scoreList.add(t[0] + t[1]);
}
scoreList.sort(Comparator.reverseOrder());
int[] answer = new int[score.length];
for(int i=0; i<score.length; i++){
answer[i] = scoreList.indexOf(score[i][0] + score[i][1])+1;
}
return answer;
}
}
- 평균이 중복돼도 indexOf()는 가장 작은 인덱스가 나오므로 상관없다.