본문 바로가기
알고리즘/JAVA

4. Least Recently Used

by vivi 2021. 9. 25.
import java.util.*;

class Main {
	public int[] solution(int S, int N, int[] arr) {
		int[] cache = new int[S];
		for (int i = 0; i < N; i++) {
			boolean check = true;
			int tmp = arr[i];
			for (int j = 0; j < S; j++) {
				if (tmp == cache[j]) {
					check = false;
					for (int k = j; k > 0; k--) {
						cache[k] = cache[k - 1];
					}
					cache[0] = tmp;
				}
			}
			if (check) {
				for (int j = S - 1; j > 0; j--) {
					cache[j] = cache[j - 1];
				}
				cache[0] = tmp;
			}
		}
		return cache;
	}

	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		int S = kb.nextInt();
		int N = kb.nextInt();
		int[] arr = new int[N];
		for (int i = 0; i < N; i++)
			arr[i] = kb.nextInt();
		for (int x : T.solution(S, N, arr))
			System.out.print(x + " ");
		kb.close();
	}
}

 

import java.util.*;

class Main {
	public int[] solution(int S, int N, int[] arr) {
		int[] cache = new int[S];
		for (int x : arr) {
			int pos = -1;
			for (int i = 0; i < S; i++) {
				if (x == cache[i])
					pos = i;
			}
			if (pos == -1) {
				for (int i = S - 1; i > 0; i--) {
					cache[i] = cache[i - 1];
				}
			} else {
				for (int i = pos; i > 0; i--) {
					cache[i] = cache[i - 1];
				}
			}
			cache[0] = x;
		}
		return cache;
	}

	public static void main(String[] args) {
		Main T = new Main();
		Scanner kb = new Scanner(System.in);
		int S = kb.nextInt();
		int N = kb.nextInt();
		int[] arr = new int[N];
		for (int i = 0; i < N; i++)
			arr[i] = kb.nextInt();
		for (int x : T.solution(S, N, arr))
			System.out.print(x + " ");
		kb.close();
	}
}

'알고리즘 > JAVA' 카테고리의 다른 글

6. 장난꾸러기  (0) 2021.09.25
5. 중복 확인  (0) 2021.09.25
3. 삽입 정렬  (0) 2021.09.24
2. 버블 정렬  (0) 2021.09.23
1. 선택 정렬  (0) 2021.09.23

댓글