강의

멘토링

커뮤니티

Inflearn Community Q&A

souk21098141's profile image
souk21098141

asked

Introduction to Java Algorithm Problem Solving: Coding Test Preparation

4. LRU (Cache, Kakao Adaptation)

stack으로 구현

Written on

·

472

0

  • 아래 코드와 같이 stack으로 구현했는데 접근 방식이 잘못된 걸까요? 삽입 정렬이 떠오르지 않아서 이렇게 했습니다 ㅠㅠ
  • import java.io.*;
    import java.util.*;

    public class Main {
    public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    public static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    public static StringTokenizer st;
    public static void main(String[] args) throws IOException{
    st = new StringTokenizer(br.readLine()," ");
    int size = Integer.parseInt(st.nextToken());
    int num = Integer.parseInt(st.nextToken());
    st = new StringTokenizer(br.readLine()," ");

    Stack<Integer> s = new Stack<>();

    for(int i =0 ;i<num ;i++) {
    int t = Integer.parseInt(st.nextToken());
    // 먼저 이미 있는 건지 확인
    if (s.contains(t)) {
    // 이미 들어있으면 삭제하고 맨 위에 넣어
    s.remove(s.indexOf(t));
    s.push(t);
    }
    // 없는 값이 들어왔을 때
    else {
    // 일단 추가하고
    s.push(t);
    // 사이즈가 초과됐으면
    if (s.size() > size) {
    s.remove(0); // 맨 밑에꺼 삭제해
    }
    }
    }
    while(!s.isEmpty()){
    bw.write(s.pop() + " ");
    }
    bw.flush();
    br.close();
    }


    }
java코테 준비 같이 해요!

Answer 1

0

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

어떻게 했든 채점사이트를 통과했다면 상관없을 것 같습니다. 그래도 영상의 방법도 알아두시면 좋을 것 같습니다.

souk21098141's profile image
souk21098141

asked

Ask a question