[Python] 백준 Stack/Queue/Deck 문제 풀이 팁(tip) 정리

2021. 1. 28. 04:04·Coding Test(Algorithms)
목차
  1. STACK
  2. QUEUE ( 백준 10845 )
  3. DEQUE ( 백준 10866 )
반응형
Stack: 10828, 9012, 10799
Queue: 10845
Deck: 10866 

~ 목차 ~

 

STACK
1. import deque from collections
2. stack이 비어있는지 확인
3. 기본 동작들을 list로 구현하기

* boj.kr/10799 쇠막대기 *

 

QUEUE ( 백준 10845 )

1. stack과 다른 점

DEQUE ( 백준 10866 )

1. stack, queue와 다른 점


STACK

1. import deque from collections

Deque is preferred over list in the cases where we need quicker append and pop operations from both the ends of the container, as deque provides an O(1) time complexity for append and pop operations as compared to list which provides O(n) time complexity. 

 

 기본 list와 동일하게 append, pop을 사용할 수 있다. 하지만 list는 O(N)의 시간 복잡도, depue는 O(1)의 시간복잡도 이므로 시간 초과가 생기는 등의 경우에 

stack=deque()를 사용한다.

 

2. stack이 비어있는지 확인

if(not stack):

 

3. 기본 동작들을 list로 구현하기

- push: append

- pop: print( list.pop() )

- size: len

- top: list[-1]

 

* boj.kr/10799 쇠막대기 *

아이디어: 스택을 사용하는건 생각하기 쉬우나, 레이저가 나타날 때마다 막대수를 더하는 게 어렵다. '(' 의 갯수만큼 더하고 ')' 나올때마다 +1 한다.


QUEUE ( 백준 10845 )

1. stack과 다른 점

- 둘다 list로 구현할 수 있으나 append대신 insert(0, number)을 사용해서 먼저 삽입한 값이 뒤로 가도록 차례로 밀어준다.

 

* attributeError: 없는 메소드를 썼을 때(자꾸 오타가 난다.. 유의! )

import sys
n=int(sys.stdin.readline().rstrip())
queue=[]

for _ in range(n):
    input=sys.stdin.readline().rstrip().split()
    mention=input[0]
    
    if mention=="push":
        queue.insert(0,input[1])
        
    elif mention=="pop":
        if(not queue):
            print(-1)
        else:
            print(queue.pop())
            
    elif mention=="size":
        print(len(queue))
        
    elif mention=="empty":
        if (not queue):
            print(1)
        else:
            print(0)
            
    elif mention=="front":
        if(not queue):
            print(-1)
        else:
            print(queue[-1])
            
    elif mention=="back":
        if(not queue):
            print(-1)
        else:
            print(queue[0])

DEQUE ( 백준 10866 )

1. stack, queue와 다른 점

- 셋다 list로 구현할 수 있으나 pop할 때 deque.pop(0) 로 인덱스를 지정해서 pop_back을 처리해준다.

import sys

n=int(sys.stdin.readline().rstrip())
deque=[]

for _ in range(n):
    input=sys.stdin.readline().rstrip().split()
    mention=input[0]
    
    if mention=="push_front":
        deque.append(input[1])
        
    elif mention=="push_back":
        deque.insert(0,input[1])
        
    elif mention=="pop_front":
        if (not deque):
            print(-1)
        else:
            print(deque.pop())
            
    elif mention=="pop_back":
        if (not deque):
            print(-1)
        else:
            print(deque.pop(0))
            
    elif mention=="size":
        print(len(deque))
        
    elif mention=="empty":
        if (not deque):
            print(1)
        else:
            print(0)
            
    elif mention=="front":
        if (not deque):
            print(-1)
        else:
            print(deque[-1])
            
    elif mention=="back":
        if (not deque):
            print(-1)
        else:
            print(deque[0])

 

 

 

소통하고 싶은 내용이 있으면 언제든 댓글주세요.

반응형
저작자표시 (새창열림)

'Coding Test(Algorithms)' 카테고리의 다른 글

[JAVA] 입출력 예제 - 백준 1000  (0) 2021.06.15
[Python] 백준 11576 - Base Conversion, 반례,오답 피드백  (0) 2021.02.02
[Python] 백준 문자열(Strings), Linked-Lists 문제 풀이 팁(tip) 정리  (0) 2021.01.29
[Python] 백준 정렬 (sorting) 기본 문제, 답, 풀이 팁(tip) 정리  (0) 2021.01.27
Greedy1. 프로그래머스 체육복 (파이썬 풀이)  (0) 2020.09.23
  1. STACK
  2. QUEUE ( 백준 10845 )
  3. DEQUE ( 백준 10866 )
'Coding Test(Algorithms)' 카테고리의 다른 글
  • [Python] 백준 11576 - Base Conversion, 반례,오답 피드백
  • [Python] 백준 문자열(Strings), Linked-Lists 문제 풀이 팁(tip) 정리
  • [Python] 백준 정렬 (sorting) 기본 문제, 답, 풀이 팁(tip) 정리
  • Greedy1. 프로그래머스 체육복 (파이썬 풀이)
RED BEAN
RED BEAN
웹 프론트엔드 개발블로그입니다. 대화하고싶으시다면 댓글 혹은 ghdqlsdl9633@gmail.com 이메일주시면 감사히 답변하겠습니다. [GitHub - https://github.com/Hong-been]
반응형
RED BEAN
REDBEAN
RED BEAN
전체
오늘
어제
  • 분류 전체보기 (102)
    • 계속하는개발 (6)
    • Development (45)
    • Coding Test(Algorithms) (47)
    • Info. (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리자

공지사항

인기 글

태그

  • MongoDB
  • 회고
  • 프론트엔드
  • 코테
  • nestjs
  • 노마드코더
  • 오블완
  • html
  • 코딩테스트
  • 자바입출력
  • Flask
  • 플라스크웹개발
  • 글또
  • 온라인강의
  • 모던자바스크립트딥다이브
  • React
  • pymongo
  • 자바스크립트
  • node
  • 티스토리챌린지
  • 이직
  • 스파르타코딩클럽
  • 코딩강의
  • css
  • 국비학원
  • 개발자
  • 백준
  • 자바
  • JS
  • 웹개발

최근 댓글

최근 글

hELLO· Designed By정상우.v4.5.2
RED BEAN
[Python] 백준 Stack/Queue/Deck 문제 풀이 팁(tip) 정리

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.