[Java] 백준 18258 큐2

Lee GaEun·2024년 12월 3일

[Java] 알고리즘

목록 보기
26/93

18258 큐2 문제 링크

문제분석

  • 정수를 저장하는 큐를 구현한 다음, 입력으로 주어지는 명령을 처리하는 프로그램을 작성
    • push X: 정수 X를 큐에 넣음
    • pop: 큐에서 가장 앞에 있는 정수를 빼고, 그 수를 출력
      • 큐에 정수가 없는 경우 -1을 출력
    • size: 큐에 들어있는 정수의 개수를 출력
    • empty: 큐가 비어있으면 1, 아니면 0을 출력
    • front: 큐의 가장 앞에 있는 정수를 출력
      • 큐에 정수가 없는 경우 -1을 출력
    • back: 큐의 가장 뒤에 있는 정수를 출력
      • 큐에 정수가 없는 경우 -1을 출력

제약 사항

입력 조건

  • 첫째 줄 : 명령의 수 N (1 ≤ N ≤ 2,000,000)
  • 둘째 줄 : 명령

출력 조건

  • 출력해야하는 명령이 주어질 경우, 한 줄에 하나씩 출력

#1

import javax.swing.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        int N = sc.nextInt();
        ArrayList<Integer> arr = new ArrayList();

        for(int i=0; i<N; i++) {
            String command = sc.next();
            if(command.equals("push")) arr.add(sc.nextInt());

            else if (command.equals("pop")) {
                if(arr.isEmpty()) System.out.println("-1");
                else {
                System.out.println(arr.get(0));
                arr.remove(0);
                }

            } else if (command.equals("size")) {
                System.out.println(arr.size());

            } else if (command.equals("empty")) {
                if(arr.isEmpty()) System.out.println("1");
                else System.out.println("0");

            } else if (command.equals("front")) {
                if(arr.isEmpty()) System.out.println("-1");
                else System.out.println(arr.get(0));

            } else if (command.equals("back")) {
                if(arr.isEmpty()) System.out.println("-1");
                else System.out.println(arr.get(arr.size()-1));
            }
        }
    }
}

  • 로직상 시간초과 날 일이 없는데 시간초과 남

#2

  • ArrayList 말고 Deque 자료형을 사용해서 구현
  • println으로 출력이 오래 걸린다고 해서 BufferedWriter로 변경
import javax.swing.*;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.*;

public class Main {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) throws IOException {
        int N = sc.nextInt();
        Deque<Integer> arr = new ArrayDeque<>();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        for(int i=0; i<N; i++) {
            String command = sc.next();

            if(command.equals("push")) {
                arr.addLast(sc.nextInt());
            }

            else if (command.equals("pop")) {
                bw.write((arr.isEmpty() ? "-1" : arr.pollFirst()) + "\n");

            } else if (command.equals("size")) {
                bw.write(arr.size() + "\n");

            } else if (command.equals("empty")) {
                bw.write((arr.isEmpty() ? "1" : "0") + "\n");

            } else if (command.equals("front")) {
                bw.write((arr.isEmpty() ? "-1" : arr.peekFirst()) + "\n");

            } else if (command.equals("back")) {
                bw.write((arr.isEmpty() ? "-1" : arr.peekLast()) + "\n");
            }
        }

        bw.flush();
        bw.close();
    }
}

  • 근데도 시간초과가 나네..

#3

  • Scanner로 읽는 것도 오래 걸린다고 해서 BufferedReader로 변경
import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        Deque<Integer> arr = new ArrayDeque<>();
        
        int N = Integer.parseInt(br.readLine());

        for (int i = 0; i < N; i++) {
            String[] command = br.readLine().split(" ");

            if (command[0].equals("push")) {
                arr.addLast(Integer.parseInt(command[1]));
            } else if (command[0].equals("pop")) {
                bw.write((arr.isEmpty() ? "-1" : arr.pollFirst()) + "\n");
            } else if (command[0].equals("size")) {
                bw.write(arr.size() + "\n");
            } else if (command[0].equals("empty")) {
                bw.write((arr.isEmpty() ? "1" : "0") + "\n");
            } else if (command[0].equals("front")) {
                bw.write((arr.isEmpty() ? "-1" : arr.peekFirst()) + "\n");
            } else if (command[0].equals("back")) {
                bw.write((arr.isEmpty() ? "-1" : arr.peekLast()) + "\n");
            }
        }

        bw.flush();
        bw.close();
    }
}

  • 성공
profile
I will give it my all (๑•̀o•́๑)ง

0개의 댓글