11import java .util .*;
22class Solution {
33 public int [] solution (String [] operations ) {
4- // key 값을 기준으로 정렬된 TreeMap
54 TreeMap <Integer ,Integer > map = new TreeMap <>();
6-
7- for (String operation : operations ){
8- String [] params = operation .split (" " );
9- String command = params [ 0 ]; // 명령어
10- int number = Integer . parseInt ( params [ 1 ]); // 숫자
11- if (command .equals ("I" )){ // 삽입 명령어
12- map .put (number , map .getOrDefault (number ,0 ) + 1 );
13- } else { // 삭제 명령어
14- if (map .size () > 0 ){
15- if (number > 0 ) { // 최댓값 삭제
16- int lastKey = map .lastKey ();
17- int cnt = map .get (lastKey );
18- if (cnt == 1 ){
19- map .remove ( lastKey );
20- } else {
21- map .put ( lastKey , cnt - 1 );
22- }
23- } else { // 최솟값 삭제
24- int firstKey = map .firstKey ();
25- int cnt = map .get (firstKey );
26- if (cnt == 1 ){
27- map .remove ( firstKey );
28- } else {
29- map .put ( firstKey , cnt - 1 );
30- }
31- }
5+
6+ for (String operation : operations ){
7+ String command = operation .split (" " )[ 0 ] ;
8+ int number = Integer . parseInt ( operation . split ( " " )[ 1 ]);
9+
10+ if (command .equals ("I" )){
11+ map .put (number ,map .getOrDefault (number ,0 ) +1 );
12+ } else {
13+ if (map .size () > 0 ){
14+ if (number == - 1 ) { // 최솟값 제거
15+ int firstKey = map .firstKey ();
16+ int cnt = map .get (firstKey );
17+ if (cnt > 1 ) {
18+ map .put ( firstKey , cnt - 1 );
19+ } else {
20+ map .remove ( firstKey );
21+ }
22+ } else { // 최댓값 제거
23+ int lastKey = map .lastKey ();
24+ int cnt = map .get (lastKey );
25+ if (cnt > 1 ) {
26+ map .put ( lastKey , cnt - 1 );
27+ } else {
28+ map .remove ( lastKey );
29+ }
30+ }
3231 }
3332 }
3433 }
35- if (map .size () == 0 ) return new int []{0 ,0 };
36-
37- return new int []{map .lastKey (), map .firstKey ()};
34+ if (map .size () == 0 ) return new int []{0 ,0 };
35+ return new int []{map .lastKey (),map .firstKey ()};
3836 }
3937}
0 commit comments