Search
Duplicate
📒

[Programmers] 02-1. 프로세스

상태
완료
수업
Algorithm Solving
주제
Programmers
4 more properties
참고

문제해설

NOTE
입력 값 ⇒ propertities 정수 1차원배열(우선도), location 정수 값 (몇번쨰로 실행되는지 알고싶은 프로세스)
출력 값 ⇒ location에 출력되는 프로세스 출력

문제 로직고민

NOTE
문제를 대충 읽고 풀려고 하지 말자.
처음에는 단순한 우선순위 큐 문제인줄 알았는데, 그런식으로 푸니깐 정답이 아니었다.
int[]를 담는 우선순위 큐에, 우선순위-들어온 순서 대로 정렬하는 방식을 사용했다.
위의 안내 사항대로 코드로 다시 짜는데 시간이 결국 더 투자되었다.
위의 안내사항을 따르기 위해 Queue를 하나 생성하고, 우선순위가 가장 높은값을 알기위해 MaxHeap(우선순위 큐)를 하나 생성한다.
queue가 빌때까지 다음과 같이 탐색한다.
1.
현재 나온 프로세스보다 우선순위가 더 높은게 큐에 있는가?
2.
있다면 다시 큐에 넣어주고, 없다면 그대로 꺼내서 종료시킨다. 이 과정에서 maxHeap의 최대값도 하나 꺼낸다.
3.
이 과정중 location과 일치하는 프로세스를 만난다면 종료하고, 계산값을 반환한다.

작성코드

NOTE
import java.util.*; class Solution { public int solution(int[] priorities, int location) { Queue<int[]> q = new LinkedList(); PriorityQueue<Integer> pr = new PriorityQueue<Integer>((a,b) -> b.compareTo(a)); for(int i =0; i< priorities.length; i++){ q.offer(new int[]{i, priorities[i]}); pr.offer(priorities[i]); } int result = 0; while(!q.isEmpty()){ int[] cur = q.poll(); if(cur[1] < pr.peek()) { q.offer(cur); continue; } result++; pr.poll(); if(cur[0] == location) break; } return result; } }
Java
복사
우선순위 큐의 정렬순서를 정하는것을 잘 기억하자(유용함)

다른사람 풀이

NOTE
class Solution { public int solution(int[] priorities, int location) { int answer = 1; PriorityQueue p = new PriorityQueue<>(Collections.reverseOrder());; for(int i=0; i<priorities.length; i++){ p.add(priorities[i]); System.out.println(p); } System.out.println(p); while(!p.isEmpty()){ for(int i=0; i<priorities.length; i++){ if(priorities[i] == (int)p.peek()){ if(i == location){ return answer; } p.poll(); answer++; } } } return answer; } }
Java
복사
Queue를 하나만 사용함
이런 방법이 있다는 정도만 참고하면 될것같다.