Post

PriorityQueue

๐Ÿ™‹โ€โ™‚๏ธ ๋“ค์–ด๊ฐ€๋ฉฐ

์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” PriorityQueue๋ฅผ ๋ฐฐ์›Œ๋ณด์ž

Q๋Š” FIFO์ธ๋ฐ, ๊ทธ์™€ ๋‹ฌ๋ฆฌ PQ๋Š” ์ •๋ ฌ์„ ํ†ตํ•ด ์˜ค๋ฆ„์ฐจ์ˆœ, ๋‚ด๋ฆผ์ฐจ์ˆœ์œผ๋กœ๋„ ๊ฐ€๋Šฅํ•˜๋‹ค

heap ๊ธฐ๋ฐ˜์œผ๋กœ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค

1
2
3
์‚ฝ์ž… (offer) -> O(log N)
์‚ญ์ œ (poll) -> O(log N)
์กฐํšŒ (peek) -> O(1)



โœ… ์ฝ”๋“œ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Main {
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		
		

		PriorityQueue<int[]> pq = new PriorityQueue<> (
				(a,b) -> a[0] - b[0]
		);
		
		pq.offer(new int[] {3, 100});
		pq.offer(new int[] {1, 200});
		pq.offer(new int[] {2, 50});
		
		while (!pq.isEmpty()) {
			int[] cur = pq.poll();
			System.out.println(Arrays.toString(cur));
		}
		
	}
}

์ถœ๋ ฅ๊ฐ’

1
2
3
[1, 200]
[2, 50]
[3, 100]


์œ„์ฒ˜๋Ÿผ a[0] - b[0] ๊ฐ€ ์•„๋‹Œ ์•ฝ๊ฐ„์˜ ๋ณ€ํ™”๋ฅผ ์ฃผ์ž

1
a[1] - b[1]

์ถœ๋ ฅ๊ฐ’

1
2
3
[2, 50]
[3, 100]
[1, 200]


๊ทธ๋ ‡๋‹ค๋ฉด ์ด๋ฒˆ์—๋Š” ๋‚ด๋ฆผ์ฐจ์ˆœ์„ ๋ณผ๊นŒ?

์•ž์ž๋ฆฌ๋งŒ ๋ฐ”๊ฟ”๋ณด์ž

1
b[0] - a[0]

์ถœ๋ ฅ๊ฐ’

1
2
3
[3, 100]
[2, 50]
[1, 200]


์ด๋ฒˆ์—๋Š” ๋’ท์ž๋ฆฌ๋ฅผ ๋ฐ”๊ฟ”๋ณด์ž

1
b[1] - a[1]

์ถœ๋ ฅ๊ฐ’

1
2
3
[1, 200]
[3, 100]
[2, 50]
This post is licensed under CC BY 4.0 by the author.

Trending Tags