-
카테고리
-
세부 분야
알고리즘 · 자료구조
-
해결 여부
미해결
stack으로 구현
22.08.03 16:50 작성 조회수 304
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();
}
}
답변을 작성해보세요.
0
답변 1