티스토리 뷰
728x90
반응형
최소값을 상수시간에 리턴하는 stack만들기. stack을 만들면서 간단히 해당 element의 상태일때 최소값을 기억해놨다가 리턴해주면 된다.
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(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
Constraints:
- -231 <= val <= 231 - 1
- Methods pop, top and getMin operations will always be called on non-empty stacks.
- At most 3 * 104 calls will be made to push, pop, top, and getMin.
class MinStack {
/** initialize your data structure here. */
int[] array = new int[30000];
int[] minArray = new int[30000];
int top = 0;
int bottom = 0;
int minVal = Integer.MAX_VALUE;
void push(int val) {
// min값 두개중에 하나에 넣는다
// 두개중에 하나에 넣는게 아니라 둘중에 큰거를 넣는다
// 그래야 제일 작은게 2개가 남는다
array[top] = val;
if (minVal > val) {
minVal = val;
}
minArray[top] = minVal;
top++;
}
void pop() {
array[top - 1] = 0;
minArray[top - 1] = 0;
top--;
if (top - 1 < 0) {
minVal = Integer.MAX_VALUE;
} else {
minVal = minArray[top - 1];
}
}
int top() {
return array[top - 1];
}
int getMin() {
return minArray[top - 1];
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/
반응형
'프로그래밍' 카테고리의 다른 글
Java - Split Array Largest Sum (Hard, LeetCode) (0) | 2021.06.26 |
---|---|
Java - Merge Sort 합병 정렬 (0) | 2021.06.03 |
LeetCode - LRU Cache (0) | 2021.06.03 |
LeetCode - 3Sum (0) | 2021.06.03 |
Semaphore와 Mutex 차이 (0) | 2021.03.14 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday