01-09 04:37
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_46 LRU(์บ์‹œ, ์นด์นด์˜ค ๋ณ€ํ˜•) ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_46 LRU(์บ์‹œ, ์นด์นด์˜ค ๋ณ€ํ˜•)

miinsun 2022. 1. 12. 16:55

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

์บ์‹œ๋ฉ”๋ชจ๋ฆฌ๋Š” CPU์™€ ์ฃผ๊ธฐ์–ต์žฅ์น˜(DRAM) ์‚ฌ์ด์˜ ๊ณ ์†์˜ ์ž„์‹œ ๋ฉ”๋ชจ๋ฆฌ๋กœ์„œ CPU๊ฐ€ ์ฒ˜๋ฆฌํ•  ์ž‘์—…์„ ์ €์žฅํ•ด ๋†“์•˜๋‹ค๊ฐ€
ํ•„์š”ํ•  ๋•Œ ๋ฐ”๋กœ ์‚ฌ์šฉํ•ด์„œ ์ฒ˜๋ฆฌ์†๋„๋ฅผ ๋†’์ด๋Š” ์žฅ์น˜์ด๋‹ค. ์›Œ๋‚™ ๋น„์‹ธ๊ณ  ์šฉ๋Ÿ‰์ด ์ž‘์•„ ํšจ์œจ์ ์œผ๋กœ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.

์ฒ ์ˆ˜์˜ ์ปดํ“จํ„ฐ๋Š” ์บ์‹œ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ ๊ทœ์น™์ด LRU ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๋”ฐ๋ฅธ๋‹ค. LRU ์•Œ๊ณ ๋ฆฌ์ฆ˜์€ Least Recently Used ์˜ ์•ฝ์ž๋กœ ์ง์—ญํ•˜์ž๋ฉด ๊ฐ€์žฅ ์ตœ๊ทผ์— ์‚ฌ์šฉ๋˜์ง€ ์•Š์€ ๊ฒƒ ์ •๋„์˜ ์˜๋ฏธ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

์บ์‹œ์—์„œ ์ž‘์—…์„ ์ œ๊ฑฐํ•  ๋•Œ ๊ฐ€์žฅ ์˜ค๋žซ๋™์•ˆ ์‚ฌ์šฉํ•˜์ง€ ์•Š์€ ๊ฒƒ์„ ์ œ๊ฑฐํ•˜๊ฒ ๋‹ค๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ž…๋‹ˆ๋‹ค.
์บ์‹œ์˜ ํฌ๊ธฐ๊ฐ€ ์ฃผ์–ด์ง€๊ณ , ์บ์‹œ๊ฐ€ ๋น„์–ด์žˆ๋Š” ์ƒํƒœ์—์„œ N๊ฐœ์˜ ์ž‘์—…์„ CPU๊ฐ€ ์ฐจ๋ก€๋กœ ์ฒ˜๋ฆฌํ•œ๋‹ค๋ฉด N๊ฐœ์˜ ์ž‘์—…์„ ์ฒ˜๋ฆฌํ•œ ํ›„ ์บ์‹œ๋ฉ”๋ชจ๋ฆฌ์˜ ์ƒํƒœ๋ฅผ ๊ฐ€์žฅ ์ตœ๊ทผ ์‚ฌ์šฉ๋œ ์ž‘์—…๋ถ€ํ„ฐ ์ฐจ๋ก€๋Œ€๋กœ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์— ์บ์‹œ์˜ ํฌ๊ธฐ์ธ S(3<=S<=10)์™€ ์ž‘์—…์˜ ๊ฐœ์ˆ˜ N(5<=N<=1,000)์ด ์ž…๋ ฅ๋œ๋‹ค.

๋‘ ๋ฒˆ์งธ ์ค„์— N๊ฐœ์˜ ์ž‘์—…๋ฒˆํ˜ธ๊ฐ€ ์ฒ˜๋ฆฌ์ˆœ์œผ๋กœ ์ฃผ์–ด์ง„๋‹ค. ์ž‘์—…๋ฒˆํ˜ธ๋Š” 1 ~100 ์ด๋‹ค.

5 9
1 2 3 2 6 2 3 5 7

์ถœ๋ ฅ - ๋งˆ์ง€๋ง‰ ์ž‘์—… ํ›„ ์บ์‹œ๋ฉ”๋ชจ๋ฆฌ์˜ ์ƒํƒœ๋ฅผ ๊ฐ€์žฅ ์ตœ๊ทผ ์‚ฌ์šฉ๋œ ์ž‘์—…๋ถ€ํ„ฐ ์ฐจ๋ก€๋กœ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

7 5 3 2 6

HINT -

 

โ€‹

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {
	public void solution(int s, int n, int [] arr) {
		Stack<Integer> stack = new Stack<>();
		
		for(int i : arr) {
			if(stack.contains(i)) {
				stack.removeElement(i);
			}
			stack.add(i);
			if(stack.size() > s) {
				stack.removeElementAt(0);
			}
		}
	
		for(int i = stack.size() - 1; i >= 0; i-- ) {
			System.out.print(stack.elementAt(i) + " ");
		}
		
		return;
	}
	
	public static void main(String[] args){
		Main main  = new Main();
		Scanner sc = new Scanner(System.in);
		
		int s = sc.nextInt();
		int n = sc.nextInt();
		int[] arr = new int[n];
		
		for(int i = 0; i < n; i++) {
			arr[i] = sc.nextInt();
		}
		
		main.solution(s, n, arr);
		
		sc.close();
		return ;
	}
}

 

 

 

Comments