JAVA/Coding Test Study
[Lv.2] 프로그래머스 - 프로세스 : Java
♡˖GYURI˖♡
2024. 5. 30. 02:12
728x90
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
이해하기
이미 한 번 풀었던 문제인데도 다시 보니 기억이 안 났다...ㅎㅎ
풀이하고 다시 보니 문제에 힌트가 다 있었다.
- 큐
- 우선순위
→ 우선순위 큐를 사용해라!
문제풀이
import java.util.*;
class Solution {
public int solution(int[] priorities, int location) {
int answer = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int p : priorities) {
pq.add(p);
}
while (!pq.isEmpty()) {
for (int i = 0; i < priorities.length; i++) {
if (priorities[i] == pq.peek()) {
pq.poll();
answer++;
if (i == location) {
return answer;
}
}
}
}
return answer;
}
}
int answer = 0;
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
우선순위 큐를 선언하는데, 선언할 때 내림차순으로 정렬할 것이라고 설정해둔다.
for (int p : priorities) {
pq.add(p);
}
priorities를 하나씩 우선순위 큐에 저장한다.
while (!pq.isEmpty()) {
for (int i = 0; i < priorities.length; i++) {
if (priorities[i] == pq.peek()) {
pq.poll();
answer++;
if (i == location) {
return answer;
}
}
}
}
priorites를 for문으로 순회하면서, priorites[i]가 우선순위 큐의 맨 앞 숫자와 같다면 우선순위 큐에서 맨 앞 숫자를 하나 poll해주고, answer++ 해준다.
만약 i가 location(타겟 위치)와 같다면 해당 프로세스를 찾은 것이니 return answer 해준다.
요즘 느끼는건데 Map이나 Queue, List 등 자료구조에 대한 심화 학습이 필요할 것 같다ㅜ