본문 바로가기
알고리즘/인프런(자바(Java) 알고리즘 문제풀이 입문

6-4 Least Recently Used

by person456 2024. 1. 14.

** 정답 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package inflearn._6_sorting_searching;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
 
public class lnflearn6_4 {
    static int n,m,k;
    static StringTokenizer st;
    static StringBuilder sb; 
    public static void main(String[] args)throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        st = new StringTokenizer(br.readLine(), " ");
        n = Integer.parseInt(st.nextToken());
        m = Integer.parseInt(st.nextToken());
        int[] arr = new int[m];
        st = new StringTokenizer(br.readLine(), " ");
        for(int i=0; i<m; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
        }
        int[] cashe = new int[n];
        for(int i=0; i<m; i++) {
            int now = arr[i];
            boolean check = false;
            int checkIndex=0;
            int checkValue=0;
            for(int j=0; j<n; j++) {
                int store = cashe[j];
                if(now==store) {
                    check=true;
                    checkIndex=j;
                    checkValue=store;
                    break;
                }
            }
            if(check) {
                for(int j=checkIndex; j>0; j--) {
                    cashe[j] = cashe[j-1];
                }
                cashe[0]=checkValue;
            }
            else {
                for(int j=n-1; j>0; j--) {
                    cashe[j] = cashe[j-1];
                }
                cashe[0]=now;
            }
        }
        sb = new StringBuilder();
        for(int i=0; i<n; i++) {
            sb.append(cashe[i]+" ");
        }
        System.out.println(sb.toString());
        br.close();
        bw.close();
    }
}
 
cs

 

- 주어진 cashe의 최대 값이 10개라는 것을 알지 못하고 생각하는데 오래 걸린 문제

- 0,1,2,3,4 라는 index가 있을 때, 각 자리의 값을 하나씩 뒤로 옮기는 방법도 쉽게 떠올리지 못했음.

--> 지금은 int배열을 통해 cashe[j] = cashe[j-1]로 진행했으나, ArrayList에는 set(index, element)라는 함수를 통해

해당 index에 어느 값을 넣는 것이 가능하지만 강의의 내용을 따라 배열로 진행.

- Hit면 index와 value의 값을 변수에 저장하고 해당 index부터 시작하여 값을 차근차근 뒤로 옮김.

- Hit가 아니면 cashe배열의 끝자락부터 1번 index까지 진행.