-
[LeetCode] 155. Min StackLeetCode 2021. 10. 25. 11:15728x90
https://leetcode.com/problems/min-stack/
Min Stack - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Min Stack - Easy

stack을 구현하는데, 필요할때마다 stack 내의 최소값을 뽑아내는 기능을 추가해야 한다.
다른 것은 stack과 같아 stack STL을 사용하면 된다.
다만, 저장 자료형을 int가 아닌 pair<int, int> 로 하여, val과 그때의 최소값을 추가해주면 된다.
그때의 최소값은 stack이 비어있을경우에는 그 val로, 비어있지 않을 경우엔 top의 최소값과 현재 val 중 작은값으로 저장을 해주자.
전체 풀이 코드
class MinStack { public: stack<pair<int, int>> st; MinStack() {while(!st.empty()) st.pop();} void push(int val) { if (st.empty()) st.push(make_pair(val, val)); else (st.push(make_pair(val, min(val, st.top().second)))); } void pop() {st.pop();} int top() {return st.top().first;} int getMin() {return st.top().second;} };'LeetCode' 카테고리의 다른 글
[LeetCode] 1417. Reformat The String (0) 2021.10.25 [LeetCode] 1007. Minimum Domino Rotations For Equal Row (0) 2021.10.25 [LeetCode] 215. Kth Largest Element in an Array (0) 2021.10.22 [LeetCode] 1812. Determine Color of a Chessboard Square (0) 2021.10.22 [LeetCode] 6. ZigZag Conversion (0) 2021.10.22