[알고리즘/백준] 18258번 : 큐 2(python)

유현민·2022년 6월 19일
0

알고리즘

목록 보기
213/253

간단하게 구현하는 문제이다.
풀이 방법이 두가지가 있는데
1. 그냥 구현
2. 투포인터 사용

구현

import sys
from collections import deque

input = sys.stdin.readline


def solution():
    q = deque()
    l = 0
    for i in range(int(input())):
        op = input().split()

        if len(op) == 2:
            q.append(int(op[1]))
            l += 1
        else:
            if op[0] == 'pop':
                if l:
                    print(q.popleft())
                    l -= 1
                else:
                    print(-1)

            elif op[0] == 'size':
                print(l)

            elif op[0] == 'empty':
                if l:
                    print(0)
                else:
                    print(1)

            elif op[0] == 'front':
                if l:
                    print(q[0])
                else:
                    print(-1)
            else:
                if l:
                    print(q[-1])
                else:
                    print(-1)


if __name__ == '__main__':
    solution()

투포인터

import sys
input = sys.stdin.readline


def solution():
    q = []
    s, e = 0, 0
    for i in range(int(input())):
        op = input().split()

        if len(op) == 2:
            q.append(int(op[1]))
            e += 1
        else:
            if op[0] == 'pop':
                if s != e:
                    print(q[s])
                    s += 1
                else:
                    print(-1)

            elif op[0] == 'size':
                print(e - s)

            elif op[0] == 'empty':
                if s != e:
                    print(0)
                else:
                    print(1)

            elif op[0] == 'front':
                if s != e:
                    print(q[s])
                else:
                    print(-1)
            else:
                if s != e:
                    print(q[e - 1])
                else:
                    print(-1)


if __name__ == '__main__':
    solution()
profile
smilegate megaport infra

0개의 댓글