728x90
18258번: 큐 2
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
풀이
처음에 back을 구현할 때, list를 사용해서 pop할 때 list.remove() 해줬는데
이렇게 구현하면 O(n) .. 이라서 시간초과가 발생한다.
그래서 Deque 사용 ~~ !
처음으로 사용해봤는데, 앞에서도 뽑을 수 있고 뒤에서도 뽑을 수 있는 게 장점인 것 같다. 👍🏻
앞에서 뽑으려면 getFisrt() / 뒤에서 뽑으려면 getLast() 사용해주면 된다.
package 백준renew;
import java.io.*;
import java.util.*;
public class 실버4_18258_큐2 {
static StringBuilder sb = new StringBuilder();
static Deque<Integer> queue = new LinkedList<>();
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
for(int tc=0; tc<N; tc++) {
String tmp = br.readLine();
String arr[] = tmp.split(" ");
if(arr[0].equals("push")) {
Push(Integer.parseInt(arr[1]));
}else if(arr[0].equals("front")) {
Front();
}else if(arr[0].equals("back")) {
Back();
}else if(arr[0].equals("size")) {
Size();
}else if(arr[0].equals("pop")) {
Pop();
}else if(arr[0].equals("empty")) {
Empty();
}
}
bw.write(sb.toString());bw.flush();bw.close();
}
static void Empty() {
if(!queue.isEmpty()) {
sb.append(0).append('\n');
}else {
sb.append(1).append('\n');
}
}
static void Pop() {
if(!queue.isEmpty()) {
int num = queue.poll();
sb.append(num).append('\n');
}else {
sb.append(-1).append('\n');
}
}
static void Size() {
sb.append(queue.size()).append('\n');
}
static void Back() {
if(!queue.isEmpty()) {
sb.append(queue.getLast()).append('\n');
}else {
sb.append(-1).append('\n');
}
}
static void Front() {
if(!queue.isEmpty()) {
sb.append(queue.getFirst()).append('\n');
}else {
sb.append(-1).append('\n');
}
}
static void Push(int x) {
queue.add(x);
}
}
728x90
'코딩테스트 > Algorithm' 카테고리의 다른 글
[BOJ] 2003: 수들의 합 2 (1) | 2024.03.22 |
---|---|
[BOJ] 14503: 로봇청소기 (JAVA) (0) | 2024.03.21 |
[BOJ] 22233: 가희와 키워드 (JAVA) (0) | 2024.03.17 |
[BOJ] 11403: 경로 찾기 (0) | 2024.03.16 |
[BOJ] 2776: 암기왕 (JAVA) (1) | 2024.03.16 |