-
[LeetCode] Min Stack (C++)알고리즘 문제풀이/LeetCode 2021. 3. 10. 00:39
leetcode.com/problems/min-stack/submissions/
최소값을 리턴하는 스택을 구현하는 문제였습니다.
/* vector */ class MinStack { public: vector<int> v; /** initialize your data structure here. */ MinStack() { } void push(int x) { v.push_back(x); } void pop() { if(!v.empty()) v.pop_back(); } int top() { if(!v.empty()) return v.back(); return NULL; } int getMin() { return *min_element(v.begin(), v.end()); } }; /** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(x); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */
/* two stack */ class MinStack { public: stack<int> s, minS; /** initialize your data structure here. */ MinStack() { } void push(int x) { s.push(x); minS.push(minS.empty() ? x : min(minS.top(), x)); } void pop() { if(!s.empty()) s.pop(); if(!minS.empty()) minS.pop(); } int top() { if(!s.empty()) return s.top(); return NULL; } int getMin() { if(!minS.empty()) return minS.top(); return NULL; } }; /** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(x); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */
'알고리즘 문제풀이 > LeetCode' 카테고리의 다른 글
[LeetCode] Majority Element (C++) (0) 2021.03.14 [LeetCode] Intersection of Two Linked Lists (C++) (0) 2021.03.11 [LeetCode] Linked List Cycle (C++) (0) 2021.03.09 [LeetCode] Maximum Depth of Binary Tree (C++) (0) 2021.03.06 [LeetCode] Merge Two Sorted Lists (C++) (0) 2021.03.04