오늘 이거 알았네요/Java
[Java] HashMap을 정렬해보자
로그관리자
2023. 7. 5. 14:15
728x90

프로그래머스 - 전국 대회 선발 고사
풀이 계획
우선 등수와 참여 여부에 따른 (true일 때) rank의 순위를 함께 담아야 하니 HashMap 필요해
rank의 길이 만큼 for문 돌려서 참여 여부가 true이면 put 하자.
이렇게 담을래
key : rank, value : 참여 여부에 따른 rank의 순위.
그리고 rank의 index 정렬해야 하는데 hashMap은 순서 보장 안 돼
그러니까 다른 자료구조 → ArrayList 에 담을 거 임
keySet()으로 담고
student map의 key값(rank)를 정렬하다... Collections.sort()
list의 0번째 1 번째 2 번째 를 각 int a / b/ c에 담고 계산 하여 answer에 담아 리턴
그래서 코드가
public class P_181851 {
public int solution(int[] rank, boolean[] attendance) {
int answer = 0;
HashMap<Integer, Integer> student = new HashMap<>();
// key : rank, value : 참여 여부에 따른 rank의 순위
for(int i = 0; i < rank.length; i++){
if(attendance[i]){ // true이면
student.put(rank[i], i);
}
}
ArrayList<Integer> studentSort = new ArrayList<>(student.keySet());
Collections.sort(studentSort);
int a = student.get(studentSort.get(0));
int b = student.get(studentSort.get(1));
int c = student.get(studentSort.get(2));
answer = 10000 * a + 100 * b + c;
return answer;
}
}
728x90