일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- self reliance
- CDD
- html
- Router
- codestate
- 객체지향
- 프론트엔드
- 원시자료형
- 회고
- Javascript #코드스테이츠
- css
- 계산기
- 자바스크립트
- css in js
- 코드스테이스
- cta button
- frontend
- 프로토타입
- JS
- 호스트인식
- 참조자료형
- WAI-ARIA
- OOP
- 개발자
- Prototype
- JavaScript
- 코드스테이츠
- cta버튼
- codestates
- condestates
- Today
- Total
jh.nrtv
[자료구조] Queue & Stack - Python으로 구현하기 본문
Queue
List기반
list의 append 메서드로 구현
# queue 선언
q = []
# enqueue O(1)
q.append(1) # [1]
q.append(2) # [1, 2]
q.append(3) # [1, 2, 3]
# dequeue O(n)
q.pop(0) # [2, 3]
q.pop(0) # [3]
Linked List 기반
python에서 이미 구현되어있는 deque(덱)이라는 자료구조가 있음
Deque 는 Double Ended QUE 의 약자로 양방향으로 enque, deque가 가능하다.
- Deque 메서드 정리
맨 앞 (왼쪽) | 맨 뒤 (오른쪽) | |
삽입 | appendleft() | append() |
제거 | popleft() | pop() |
from collections import deque
# deque 선언
q = deque()
# enqueue O(1)
q.append(1) # [1]
q.append(2) # [1, 2]
q.append(3) # [1, 2, 3]
q.appendleft(0) # [0, 1, 2, 3]
# dequeue O(1)
q.popleft() # [1, 2, 3]
q.popleft() # [2, 3]
q.pop() # [3]
Stack
LIFO
list로 구현하는 것이 가장 간단
# stack 선언
s = []
# push - O(1)
s.append(1) # [1]
s.append(2) # [1, 2]
s.append(3) # [1, 2, 3]
# pop - O(1)
s.pop() # [1, 2]
s.pop() # [1]
LIFO 예시문제 1
- 괄호 유효성 검사
Valid Parentheses - LeetCode
Can you solve this real interview question? Valid Parentheses - Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. An input string is valid if: 1. Open brackets must be closed by the sam
leetcode.com
def isValid(s):
stack=[]
for p in s:
if p=='(':
stack.append(')')
elif p=='{':
stack.append('}')
elif p=='[':
stack.append(']')
elif not stack or stack.pop()!= p: #stack이 비어있지 않고
return False
return not stack #stack이 비어있으면 True, 아니면 False
LIFO 예시문제 2
- 온도 리스트를 보고 몇일 기다리면 더 따뜻해지는지 검사하기
Daily Temperatures - LeetCode
Can you solve this real interview question? Daily Temperatures - Given an array of integers temperatures represents the daily temperatures, return an array answer such that answer[i] is the number of days you have to wait after the ith day to get a warmer
leetcode.com
class Solution(object):
def dailyTemperatures(self,temperatures):
stack=[]
ans= [0 for i in range(len(temperatures))]
i=0
while i <len(temperatures):
while stack and stack[-1][0] <temperatures[i] :
index =stack[-1][1]
ans[index] = i - index
stack.pop()
stack.append((temperatures[i],i))
i+=1
return ans
'알고리즘, 자료구조' 카테고리의 다른 글
[자료구조] 해시 테이블이란? (0) | 2023.12.16 |
---|---|
[자료구조] 재귀 (Recursion) , Tree , 트리순회 (BFS , DFS) (0) | 2023.09.19 |
[자료구조] Python의 자료구조 - list, tuple, set, dictionary( =Hash Table) (0) | 2023.09.09 |
[자료구조] Linked List- Python으로 구현하기 (0) | 2023.08.13 |
[알고리즘] 재귀 (recursion) (0) | 2022.12.15 |