카테고리 없음

[ LeetCode ][JAVA][155] MinStack

kim.svadoz 2020. 10. 5. 23:14
반응형

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

문제

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.

입력예제

Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

출력예제

[null,null,null,null,-3,null,0,-2]

예제설명

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

제한

  • Methods pop, top and getMin operations will always be called on non-empty stacks.

코드

import java.util.Stack;

public class LC155_MinStack {

      public static void main(String[] args) {
          // TODO Auto-generated method stub

      }
      /*
      3 : 1,2,3 min=1
      2 : 1,2 min=1
      1 : 1 min=1
      */
	
      class Node{
          int val, min;
          Node(int val, int min){
              this.val = val;
              this.min = min;
          }
      }
      Stack<Node> s = new Stack<>();
      /** initialize your data structure here. */

      public void push(int x) {
          Node node = null;
          if(s.isEmpty()){
              node = new Node(x, x);
          }else {
              node = new Node(x, x < s.peek().min ? x : s.peek().min);
          }
          s.push(node);
      }

      public void pop() {
          s.pop();
      }

      public int top() {
          return s.peek().val;
      }

      public int getMin() {
          return s.peek().min;
      }
}
반응형