https://www.acmicpc.net/problem/18258
18258번: 큐 2
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 2,000,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
Scanner는 사용자가 입력한 데이터를 토큰 단위로 잘라서 입력받기 때문에 시간이 오래 걸린다는 단점이 있다.
반면 BufferedReader를 사용한다면 String 단위로 입력받기 때문에 Scanner에 비해 빠르다는 장점이 있다.
참고: https://ifuwanna.tistory.com/221
[Java] String, StringBuffer, StringBuilder 차이 및 장단점
Java 에서 문자열을 다루를 대표적인 클래스로 String , StringBuffer, StringBuilder 가 있습니다. 연산이 많지 않을때는 위에 나열된 어떤 클래스를 사용하더라도 이슈가 발생할 가능성은 거의 없습니다.
ifuwanna.tistory.com
Queue Api :https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html
Queue (Java Platform SE 8 )
A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the opera
docs.oracle.com
데이터 저장 타입:
따라서 시간복잡도를 줄이기 위해 StringBuilder와 BufferedReader를 사용한다.
StringBuilder :
printf로 여러번 출력하는것 보다 출력해야할 모든 문자를 저장한 후에 한번에 출력하는 것이 시간복잡도 면에서 뛰어나기 때문에 StringBuilder로 출력해야할 데이터를 모두 저장한 후 한번에 print한다.
Integer형식의 Queue를 생성하고 이를 적절히 사용하여 코드를 구현하였다.
int와 Integer형식은 null타입의 유무에 따라 차이가 난다.
import java.util.*;
import java.io.*;
public class _18258 {
public static void main(String[] args) throws IOException {
//linked list
Queue<Integer> q = new LinkedList<Integer>();
StringBuilder strB = new StringBuilder();
BufferedReader buffR = new BufferedReader(new InputStreamReader(System.in));
int lastQ = -1, N = 0;
Integer tm;
String inputStr;
N = Integer.parseInt(buffR.readLine());
while(N-- > 0) {
StringTokenizer st = new StringTokenizer(buffR.readLine());
inputStr = st.nextToken();
switch(inputStr) {
case "push" :
lastQ = Integer.parseInt(st.nextToken());
q.offer(lastQ);
break;
case "pop" :
tm = q.peek() == null ? -1 : q.poll();
strB.append(tm);
strB.append("\n");
break;
case "size" :
strB.append(q.size());
strB.append("\n");
break;
case "empty":
strB.append( q.isEmpty() ? 1 : 0);
strB.append("\n");
break;
case "front":
tm = q.peek();
strB.append(tm == null ? -1 : tm);
strB.append("\n");
break;
case "back" :
strB.append(q.isEmpty() ? -1 : lastQ);
strB.append("\n");
break;
default:
break;
}
}
String pintStr = strB.toString();
System.out.printf("%s", pintStr);
}
}
'2022 하반기 > algorithm' 카테고리의 다른 글
백준 2226 java (0) | 2023.01.08 |
---|---|
백준 15828 java (0) | 2023.01.08 |
백준 2164 java (0) | 2023.01.08 |
댓글