<문제>
<접근 방식>
1) 실행 대기 큐 용도의 Queue(q)에 담을 클래스 MyMember를 사용해 문제에서 주어진 순서대로 q에 담는다.
2) 우선순위를 내림차순으로 정렬할 Heap(pq)에 담는다.
3) pq에서 가장 큰 우선순위 값과 q에서 뽑은 MyMember의 priority값이 같으면 q에서 해당 인스턴스를 제거하고 그렇지 않으면 다시 q에 넣는다.(반복)
<코드>
import java.util.*;
class Solution {
static class MyMember{
int priority;
int location;
public MyMember(int priority, int location) {
this.priority = priority;
this.location = location;
}
}
public int solution(int[] priorities, int location) {
int answer = 0;
Queue<MyMember> q = new LinkedList<>();
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for(int i = 0; i < priorities.length; ++i){
q.add(new MyMember(priorities[i],i));
pq.add(priorities[i]);
}
int count = 0;
while(!q.isEmpty())
{
MyMember member = q.poll();
int priority = pq.peek();
if(member.priority == priority){
pq.remove();
++count;
if(member.location == location) return count;
}
else{
q.add(member);
}
}
return count;
}
}
반응형
'코딩 테스트 > 알고리즘(Java)' 카테고리의 다른 글
[프로그래머스/Lv.2] 타겟 넘버 (0) | 2025.02.13 |
---|---|
[프로그래머스/Lv.2] 더 맵게 (1) | 2025.02.04 |
[프로그래머스/Lv.1] 두 개 뽑아서 더하기 (0) | 2025.02.04 |
[프로그래머스/Lv.2] 카펫 (0) | 2025.02.04 |
[프로그래머스/Lv.1] 가장 가까운 같은 글자 (0) | 2025.01.24 |