๐ŸŒžAlgorithm/๐Ÿ”ฅprogrammers

[programmers] ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ

๋ฟŒ์•ผ._. 2026. 7. 27. 09:26
๋ฌธ์ œ
https://school.programmers.co.kr/learn/courses/30/lessons/42628
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

SW๊ฐœ๋ฐœ์ž๋ฅผ ์œ„ํ•œ ํ‰๊ฐ€, ๊ต์œก์˜ Total Solution์„ ์ œ๊ณตํ•˜๋Š” ๊ฐœ๋ฐœ์ž ์„ฑ์žฅ์„ ์œ„ํ•œ ๋ฒ ์ด์Šค์บ ํ”„

programmers.co.kr

 

์ด ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด์„œ ์˜ˆ์ „์— ํ’€์—ˆ๋˜ ๋ฌธ์ œ๊ฐ€ ๊ธฐ์–ต์ด ์•ˆ ๋‚˜์„œ ์ฐธ๊ณ ํ–ˆ๋‹ค

https://melody-coding.tistory.com/318

 

[Baekjoon] 7662_์ด์ค‘ ์šฐ์„ ์ˆœ์œ„ ํ

Gold IV๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/7662) ๋ฌธ์ œ ํ’€์ด & ์ƒ๊ฐ ์ฒ˜์Œ์—๋Š” ์ตœ๋Œ“๊ฐ’๊ณผ ์ตœ์†Ÿ๊ฐ’์„ ๊ด€๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ 2๊ฐœ ์„ ์–ธํ•ด์„œ ์˜ค๋ฆ„์ฐจ์ˆœ, ๋‚ด๋ฆผ์ฐจ์ˆœ ์ˆœ์œผ๋กœ ์ •๋ ฌํ•ด์„œ ์‚ฌ์šฉํ–ˆ๋‹ค. ์‹œ๊ฐ„์ œ

melody-coding.tistory.com

https://melody-coding.tistory.com/317

 

[์ž๋ฃŒ๊ตฌ์กฐ] TreeMap

โ“ TreeMap ์ด๋ž€?์ด์ง„ํŠธ๋ฆฌ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•œ Map ์ปฌ๋ ‰์…˜๊ฐ์ฒด ์ €์žฅ ์‹œ ์ž๋™ ์ •๋ ฌ(default : ์˜ค๋ฆ„์ฐจ์ˆœ)   โ“TreeMap ์„ ์–ธTreeMap map=new TreeMap();  โ“ TreeMap ์ถ”๊ฐ€, ์‚ญ์ œ// ์ถ”๊ฐ€map.put(1,1);// ์‚ญ์ œmap.remove(1);   โ“ T

melody-coding.tistory.com

 


< ์ด์ค‘์šฐ์„ ์ˆœ์œ„ํ >

 

๋ฌธ์ œ ํ’€์ด (Java)

import java.util.*;

class Solution {
	public int[] solution(String[] operations) {
		int[] answer = { 0, 0 };

		TreeMap<Integer, Integer> map = new TreeMap<>();

		for (int i = 0; i < operations.length; i++) {
			String str[] = operations[i].split(" ");
			int num = Integer.parseInt(str[1]);

			if (str[0].charAt(0) == 'I') {
				if (map.containsKey(num)) {
					map.put(num, map.get(num) + 1);
				} else {
					map.put(num, 1);
				}
			} else {
				if (map.size() == 0) {
					continue;
				}
				if (num == 1) {
					if (map.lastEntry().getValue() == 1) {
						map.remove(map.lastKey());
					} else {
						map.put(map.lastKey(), map.get(map.lastKey()) - 1);
					}
				} else {
					if (map.firstEntry().getValue() == 1) {
						map.remove(map.firstKey());
					} else {
						map.put(map.firstKey(), map.get(map.firstKey()) - 1);
					}
				}
			}
		}

		if (!map.isEmpty()) {
			answer[0] = map.lastKey();
			answer[1] = map.firstKey();
		}
		return answer;
	}
}

 

TreeMap์„ ์„ ์–ธํ•œ ํ›„ operations๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉฐ ๋‹ค์Œ ๊ณผ์ •์„ ๊ฑฐ์นœ๋‹ค.

 

1. I๋ผ๋ฉด map์— ์ถ”๊ฐ€

2. D์ด๊ณ  map์ด ๋น„์—ˆ๋‹ค๋ฉด ๋‹ค์Œ ๋ช…๋ น์–ด๋กœ ๋„˜์–ด๊ฐ€๊ธฐ

3. D์ด๊ณ  1์ด๋ผ๋ฉด ์ตœ๋Œ“๊ฐ’ ์‚ญ์ œ, -1์ด๋ผ๋ฉด ์ตœ์†Ÿ๊ฐ’ ์‚ญ์ œ

 

์ตœ์ข… TreeMap์ด ๋น„์–ด์žˆ์ง€ ์•Š๋‹ค๋ฉด ์ตœ๋Œ“๊ฐ’๊ณผ ์ตœ์†Ÿ๊ฐ’์„ answer์— ์ €์žฅํ•œ ํ›„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

 



 

์ถœ์ฒ˜: ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋”ฉ ํ…Œ์ŠคํŠธ ์—ฐ์Šต, 
https://school.programmers.co.kr/learn/challenges