Least Recently Used

brightvvater·2023년 3월 14일

풀이>

import java.util.*;
public 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++) { //cache를 돌면서 hit 가 있는지 확인
                if(x == cache[i]) pos = i; 
            }
            if (pos == -1) { //hit 가 없으면 위치 하나씩 뒤로 옮기기
                for (int i = s - 1; i >= 1; i--) {
                    cache[i] = cache[i - 1];
                }
                cache[0] = x;// 새로운 작업 첫자리에 넣기
            }else { //hit가 있으면 hit 자리서부터 뒤로 옮기기
                for (int i = pos; i >= 1; 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 + " ");
        }
    }
}
profile
코딩을 잘하고 싶은 입문자

0개의 댓글