티스토리 뷰
https://leetcode.com/problems/implement-queue-using-stacks/
1. 문제분석
2개의 스택으로 큐 인터페이스 구현 -> push,pop,peek,empty
2. 풀어보기
['MyQueue','push','push','peek','pop','empty']
[[],[1],[2],[],[],[]]
-> [null,null,null,1,1,false]
3. 슈도코드
stack에 push, reverse에서 pop&peek -> reverse가 비워지는 시점에 stack을 reverse에 뒤집어 부음
사실 이 코드 그대로 써도 Accepted 뜸 -> 언어 내장 큐/덱을 사용하지 않고 구현하는 문제
class MyQueue {
private queue: number[];
constructor() {
this.queue = [];
}
push(x: number): void {
this.queue.push(x);
}
pop(): number {
return this.queue.shift()!;
}
peek(): number {
return this.queue[0];
}
empty(): boolean {
return this.queue.length === 0;
}
}
4. 구현코드
class MyQueue; // 큐 구현은 https://ha2el.tistory.com/40 참고
5. 풀이회고
처음에는 stack에 붓고, 뽑을 때 마다 reverse를 해서 top을 뽑고 버리고 다시 담는 구현했다.
현재 코드는 해설을 참고해서 다시 짜본 코드이다. 어떻게 이런 발상을 하는지.. 보고 따라하기는 쉬운데, 생각해내기는 어렵다.
로직을 고민할 때 뇌를 말랑말랑하게 유연하게 고민해볼 필요가 있는 것 같다.
'자료구조 & 알고리즘 > LeetCode' 카테고리의 다른 글
feat: [Easy] Diameter of Binary Tree (JS/TS) (0) | 2024.06.26 |
---|---|
feat: [Easy] Maximum Depth of Binary Tree (JS/TS) (0) | 2024.06.26 |
feat: [Med.] Top K Frequent Elements (JS/TS) (0) | 2024.06.26 |
feat: [Med.] K Closest Points to Origin (JS/TS) (0) | 2024.06.17 |
feat: [Med.] Longest Substring Without Repeating Characters (JS/TS) (1) | 2024.06.17 |