Algorithm
[Leetcode] 155. Min Stack
딸기검
2022. 3. 5. 22:53
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object.
void push(int val) pushes the element val onto the stack.
void pop() removes the element on the top of the stack.
int top() gets the top element of the stack.
int getMin() retrieves the minimum element in the stack.
Example 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]
Output
[null,null,null,null,-3,null,0,-2]
Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top(); // return 0
minStack.getMin(); // return -2
난이도: easy
간단한 스택구현이다
push, pop, top, getMin 4가지 구현이고
top은 스택에서 가장 마지막에 들어온 숫자를 return 해주고, getMin은 스택내부에서 가장 작은 숫자를 return 해준다
MinStack.prototype.push = function(val) {
this.stack.push(val)
};
/**
* @return {void}
*/
MinStack.prototype.pop = function() {
this.stack.pop()
};
/**
* @return {number}
*/
MinStack.prototype.top = function() {
return this.stack[this.stack.length - 1];
};
/**
* @return {number}
*/
MinStack.prototype.getMin = function() {
let min = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < this.stack.length; i++) {
const value = this.stack[i];
if (min > value) {
min = value
}
}
return min
};
정말 간단하게 stack구현이라 금방 풀었다
반응형