File tree Expand file tree Collapse file tree 1 file changed +64
-0
lines changed
minjeong/Stack, Queue, Priority Queue Expand file tree Collapse file tree 1 file changed +64
-0
lines changed Original file line number Diff line number Diff line change 1+ import heapq
2+
3+
4+ def solution (operations ):
5+ min_heap = []
6+ max_heap = []
7+ number_count = {} # 각 숫자가 큐에 몇 번 남았는지 카운트
8+ size = 0 # 현재 큐에 남아있는 총 원소 수
9+
10+ for op in operations :
11+ cmd , num_str = op .split (' ' )
12+ num = int (num_str )
13+
14+ if cmd == 'I' :
15+ # 삽입
16+ heapq .heappush (min_heap , num )
17+ heapq .heappush (max_heap , - num )
18+ number_count [num ] = number_count .get (num , 0 ) + 1
19+ size += 1
20+ else : # cmd == 'D'
21+ if size == 0 :
22+ # 큐가 비어있다면 연산 무시
23+ continue
24+
25+ if num == 1 :
26+ # 최댓값 삭제
27+ while max_heap :
28+ x = - heapq .heappop (max_heap )
29+ if number_count .get (x , 0 ) > 0 :
30+ # num이 1번 이상 등장했다면, 카운트 반영
31+ number_count [x ] -= 1
32+ size -= 1
33+ break
34+ else :
35+ # num == -1, 최솟값 삭제
36+ while min_heap :
37+ x = heapq .heappop (min_heap )
38+ if number_count .get (x , 0 ) > 0 :
39+ # num이 1번 이상 등장했다면, 카운트 반영
40+ number_count [x ] -= 1
41+ size -= 1
42+ break
43+
44+ # 연산 후 큐가 비어있다면 [0, 0]
45+ if size == 0 :
46+ return [0 , 0 ]
47+
48+ # 남아있는 최댓값 찾기
49+ max_value = 0
50+ while max_heap :
51+ x = - heapq .heappop (max_heap )
52+ if number_count .get (x , 0 ) > 0 :
53+ max_value = x
54+ break
55+
56+ # 남아있는 최솟값 찾기
57+ min_value = 0
58+ while min_heap :
59+ x = heapq .heappop (min_heap )
60+ if number_count .get (x , 0 ) > 0 :
61+ min_value = x
62+ break
63+
64+ return [max_value , min_value ]
You can’t perform that action at this time.
0 commit comments