-
[힙] 이중우선순위큐Study/Coding Test 2021. 2. 11. 11:29
programmers.co.kr/learn/courses/30/lessons/42628
코딩테스트 연습 - 이중우선순위큐
programmers.co.kr
문제 설명
이중 우선순위 큐는 다음 연산을 할 수 있는 자료구조를 말합니다.
명령어수신 탑(높이) I 숫자 큐에 주어진 숫자를 삽입합니다. D 1 큐에서 최댓값을 삭제합니다. D -1 큐에서 최솟값을 삭제합니다. 이중 우선순위 큐가 할 연산 operations가 매개변수로 주어질 때, 모든 연산을 처리한 후 큐가 비어있으면 [0,0] 비어있지 않으면 [최댓값, 최솟값]을 return 하도록 solution 함수를 구현해주세요.
제한사항
- operations는 길이가 1 이상 1,000,000 이하인 문자열 배열입니다.
- operations의 원소는 큐가 수행할 연산을 나타냅니다.
- 원소는 “명령어 데이터” 형식으로 주어집니다.- 최댓값/최솟값을 삭제하는 연산에서 최댓값/최솟값이 둘 이상인 경우, 하나만 삭제합니다.
- 빈 큐에 데이터를 삭제하라는 연산이 주어질 경우, 해당 연산은 무시합니다.
입출력 예
operations return [I 16,D 1] [0,0] [I 7,I 5,I -5,D -1] [7,5] 입출력 예 설명
- 16을 삽입 후 최댓값을 삭제합니다. 비어있으므로 [0,0]을 반환합니다.
- 7,5,-5를 삽입 후 최솟값을 삭제합니다. 최대값 7, 최소값 5를 반환합니다.
Sol 1) vector 이용
#include <string> #include <vector> #include <algorithm> using namespace std; vector<int> solution(vector<string> operations) { vector<int> answer; vector<int> v; for(int i=0; i<operations.size(); i++){ if(operations[i][0] == 'I'){ int pos = operations[i].find(' '); string substring = operations[i].substr(pos+1); v.push_back(stoi(substring)); } else if (operations[i].substr(0,4) == "D -1"){ if(!v.empty()){ auto minVal = min_element(v.begin(), v.end()); v.erase(minVal); } } else if (operations[i].substr(0,3) == "D 1"){ if(!v.empty()){ auto maxVal = max_element(v.begin(), v.end()); v.erase(maxVal); } } } if(!v.empty()){ sort(v.begin(), v.end()); answer.push_back(v[v.size()-1]); answer.push_back(v[0]); return answer; } return vector<int> (2,0); }
Sol2) multiset 이용
#include <string> #include <vector> #include <iostream> #include <set> using namespace std; vector<int> solution(vector<string> arguments) { vector<int> answer = {0, 0}; set <int> pq; for (auto s : arguments){ if (s[0] == 'I'){ int num = stoi(s.substr(2, s.size())); pq.insert(num); } else{ if (s[2] == '1'){ auto it = pq.end(); if (it != pq.begin()){ it--; pq.erase(it); } } else{ auto it = pq.begin(); if (it != pq.end()){ pq.erase(it); } } } } if (pq.size() > 0){ answer[0] = *pq.rbegin(); answer[1] = *pq.begin(); } return answer; }
이 문제는 multiset을 이용하면 간편하게 해결된다.
set은 연관 컨테이너이고, 균형 이진 트리로 구현된다.
즉, 삽입과 동시에 정렬되므로 빠르게 검색 가능하다.
multiset은 set과 동일하지만, 중복된 key를 허용한다.
'Study > Coding Test' 카테고리의 다른 글
[2021 KAKAO] 순위 검색 (0) 2021.02.15 [2021 KAKAO] 신규 아이디 추천 (0) 2021.02.11 [힙] 디스크 컨트롤러 (0) 2021.02.11 [BFS/DFS] 여행경로 (0) 2021.02.10 [BFS/DFS] 단어변환 (0) 2021.02.10