문제를 읽어보면 location이 priorities배열의 index를 가리키고 있다는 것을 알 수 있다.
이 점을 어떻게 이용할까 고민하다 배열의 index와 그 index가 가리키고 있는 값을 키와 값으로 묶어 Hashmap으로 구현해 보기로 마음먹고 문제를 풀었다.
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 0;
Map<Integer, Integer> printHm = new HashMap<>();
// 배열의 index를 key, 그 값을 value로 분류
for(int i=0;i<priorities.length;i++){
printHm.put(i, priorities[i]);
}
// 최우선으로 인쇄하는 값을 지정해줬다.
int topPriority = Collections.max(printHm.values());
while(true){
for(int key : printHm.keySet()){
// 배열을 돌다 나온 값이 최우선 순위와 같을 경우
if(printHm.get(key) == topPriority){
// 최우선 순위 값이 먼저 인쇄되므로 1장을 인쇄한다(answer++).
answer++;
// 인쇄 후 그 key와 location이 같을 경우
if(key == location){
// 찾고 있던 값이므로 답을 반환!
return answer;
}
// 그렇지 않으면 해당 key에 있는 값을 0이라는 최솟값으로 두고
printHm.replace(key, 0);
// 최우선 순위를 다시 설정해준다.
topPriority = Collections.max(printHm.values());
}
}
}
}
}
while 조건문을 세울 때 일단 돌리고 보자는 마음에 true로 설정해 두었는데,
코드를 짜다보니 결국 안쪽에서 답을 반환해줘서 true로 돌려도 괜찮겠다는 마음에 그대로 두었다.
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 0;
Map<Integer, Integer> printHm = new HashMap<>();
for(int i=0;i<priorities.length;i++){
printHm.put(i, priorities[i]);
}
int topPriority = Collections.max(printHm.values());
while(true){
for(int key : printHm.keySet()){
if(printHm.get(key) == topPriority){
answer++;
if(key == location){
return answer;
}
printHm.replace(key, 0);
topPriority = Collections.max(printHm.values());
}
}
}
}
}
나름 직관적이고 깔끔하게 나온 것 같다! ㅎㅎ
문제를 풀면서 느끼는 건 자료형이 확실히 정해져 있는 언어로 코드를 짜는게 생각보다 어렵다는 것이다..😂