1. 문제 및 예시
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
Example:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> Returns -3.
minStack.pop();
minStack.top(); --> Returns 0.
minStack.getMin(); --> Returns -2.
2. 풀이
/**
* initialize your data structure here.
*/
var MinStack = function() {
this.st = [];
};
/**
* @param {number} x
* @return {void}
*/
MinStack.prototype.push = function(x) {
this.st.push(x);
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
return this.st.pop();
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.st[this.st.length-1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
return this.st.reduce((a, b)=> a > b ? b : a);
};
/**
* Your MinStack object will be instantiated and called as such:
* var obj = new MinStack()
* obj.push(x)
* obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.getMin()
*/
3. 결과
18 / 18 test cases passed.
Status: Accepted
Runtime: 140 ms
Memory Usage: 44.3 MB
반응형
'Programming' 카테고리의 다른 글
[LeetCode] [Easy] [JS] 1046. Last Stone Weight (0) | 2020.04.12 |
---|---|
[LeetCode] [Easy] [JS] 543. Diameter of Binary Tree (0) | 2020.04.12 |
[LeetCode] [Easy] [JS] 844. Backspace String Compare (0) | 2020.04.10 |
[LeetCode] [Easy] [JS] 876. Middle of the Linked List (0) | 2020.04.09 |
[LeetCode] [JS] Apr 7th. Counting Elements (0) | 2020.04.08 |