오늘의 취준/오늘의 코테

[JAVA] 알고리즘 문제풀이 입문 6-4번

gogoem 2023. 8. 8. 16:40
728x90

강의: https://inf.run/w779

 

자바(Java) 알고리즘 문제풀이 입문: 코딩테스트 대비 - 인프런 | 강의

자바(Java)로 코딩테스트를 준비하시는 분을 위한 강좌입니다. 코딩테스트에서 가장 많이 출제되는 Top 10 Topic을 다루고 있습니다. 주제와 연동하여 기초문제부터 중급문제까지 단계적으로 구성

www.inflearn.com

 

 

 

 

6-4번

import java.util.Scanner;

public class Main {
  public int[] solution(int s, int n, int[] arr){
    int[] cache = new int[s];
   
    for(int x: arr){
      int pos = s-1;
      for(int i = 0; i < s; i++){
        if(cache[i] == x){ pos = i; }
      }
      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 in = new Scanner(System.in);

    int s = in.nextInt();
    int n = in.nextInt();
    int[] arr = new int[n];
    for(int i = 0; i < n; i++){
      arr[i] = in.nextInt();
    }
    in.close();

    for(int x : t.solution(s, n, arr))
      System.out.print(x+" ");
  }
}