[programmers/c#] [level 3] 이중우선순위큐 - 42628
[level 3] 이중우선순위큐 - 42628
성능 요약
메모리: 47.9 MB, 시간: 427.45 ms
구분
코딩테스트 연습 > 힙(Heap)
채점결과
정확성: 100.0
합계: 100.0 / 100.0
제출 일자
2025년 11월 27일 16:53:57
문제 설명
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
| 명령어 | 수신 탑(높이) |
|---|---|
| I 숫자 | 큐에 주어진 숫자를 삽입합니다. |
| D 1 | 큐에서 최댓값을 삭제합니다. |
| D -1 | 큐에서 최솟값을 삭제합니다. |
이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
제한사항
- operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
- operations의 원소는 큐가 수행할 연산을 나타냅니다.
- 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
- 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.
입출력 예
| operations | return |
|---|---|
| ["I 16", "I -5643", "D -1", "D 1", "D 1", "I 123", "D -1"] | [0,0] |
| ["I -45", "I 653", "D 1", "I -642", "I 45", "I 97", "D 1", "D -1", "I 333"] | [333, -45] |
입출력 예 설명
입출력 예 #1
- 16과 -5643을 삽입합니다.
- 최솟값을 삭제합니다. -5643이 삭제되고 16이 남아있습니다.
- 최댓값을 삭제합니다. 16이 삭제되고 이중 우선순위 큐는 비어있습니다.
- 우선순위 큐가 비어있으므로 최댓값 삭제 연산이 무시됩니다.
- 123을 삽입합니다.
- 최솟값을 삭제합니다. 123이 삭제되고 이중 우선순위 큐는 비어있습니다.
따라서 [0, 0]을 반환합니다.
입출력 예 #2
- -45와 653을 삽입후 최댓값(653)을 삭제합니다. -45가 남아있습니다.
- -642, 45, 97을 삽입 후 최댓값(97), 최솟값(-642)을 삭제합니다. -45와 45가 남아있습니다.
- 333을 삽입합니다.
이중 우선순위 큐에 -45, 45, 333이 남아있으므로, [333, -45]를 반환합니다.
※ 공지 - 2024년 7월 22일 테스트케이스가 추가되었습니다. 기존에 제출한 코드가 통과하지 못할 수도 있습니다.
출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges
// 이중 우선순위 큐
// input 분리 switch-> 확인 [v]
// insert시 max,min힙에 둘다 저장 // PriorityQueue 사용불가 -> SortedDictionary로 변경
//
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
SortedDictionary<int,int> map = new SortedDictionary<int,int>();
public int[] solution(string[] operations) {
// PriorityQueue<int,int> maxheap = new PriorityQueue<int,int>(); // val,-val
// PriorityQueue<int,int> minheap = new PriorityQueue<int,int>(); // val,+val
for (int i=0; i<operations.Length; i++){
string[] input = operations[i].Split();
char type = char.Parse(input[0]);
int val = int.Parse(input[1]);
switch (type){
case 'I':
// Console.WriteLine($"I {type}:{val}");
Insert(val);
break;
case 'D':
if (val==1){
// Console.WriteLine($"1 {type}:{val}");
DeleteMax();
}
else{
// Console.WriteLine($"-1 {type}:{val}");
DeleteMin();
}
break;
}
}
if (map.Count == 0){
return new int[] {0,0};
} else{
return new int[] {map.Last().Key, map.First().Key};
}
}
void Insert(int x){
if (!map.ContainsKey(x)) map[x] = 0;
map[x]++;
}
void DeleteMin(){
if (map.Count == 0) return;
int key = map.First().Key;
if (map[key] == 1) map.Remove(key);
else map[key]--;
}
void DeleteMax(){
if (map.Count == 0) return;
int key = map.Last().Key;
if (map[key] == 1) map.Remove(key);
else map[key]--;
}
}
처음에는 PriorityQueue로 구현하려고 했으나, 해당 ide에는 지원하지않아 SortedDictionary로 구현하였다.
다른사람의 풀이
다른사람의 풀이중에 리스트로 구현한 코드가 있어 분석해봤다.
using System;
using System.Collections;
using System.Collections.Generic;
public class Solution {
public int[] solution(string[] operations) {
int[] answer = new int[2];
List<int> inListArr = new List<int>();
foreach (string sOper in operations)
{
string[] sOperArr = sOper.Split(" ");
int check = Int16.Parse(sOperArr[1]);
switch (sOperArr[0])
{
case "I":
inListArr.Add(check);
break;
case "D":
if (inListArr.Count > 0)
{
inListArr.Sort();
inListArr.RemoveAt(check == 1 ? inListArr.Count - 1 : 0);
}
break;
}
}
if (inListArr.Count == 0)
{
answer[0] = 0;
answer[1] = 0;
}
else
{
inListArr.Sort();
answer[0] = inListArr[inListArr.Count - 1];
answer[1] = inListArr[0];
}
return answer;
}
}
근데 지금보면 삭제할때 정렬 후에 제거해주고있는데,, 정렬시 퀵솔트 O(nlogn) 이라고 해도, 최악의 경우 모든 operations가 D type이라면 O(n*nlogn)이게 된다.
입력의 개수가 최대 10^6이기 때문에, 시간초과가 뜰것이다.
SortedDictionary로 삽입시 O(logn), 최댓,최솟값제거시 O(1)이라서 기존 구현방식이 적합해보인다.