Min Stack 스택의 최소 기능

bong bong·2023년 8월 31일

알고리즘

목록 보기
19/31

개요
푸시, 팝, 상단 및 일정한 시간에 최소 요소 검색을 지원하는 스택을 설계합니다.

클래스를 구현합니다 MinStack.

MinStack()스택 개체를 초기화합니다.

private Stack<Integer> minStack;

void push(int val)요소를 val스택에 푸시합니다.

statck.push(val);
if(minStack.isEmphy()||val <= minStack.peek()){
minStack.push(val); }
}

void pop()스택 맨 위에 있는 요소를 제거합니다.

if (!stack.isEmpty()) {
if (stack.peek().equals(minStack.peek())) {
minStack.pop(); }
stack.pop();
}
int top()스택의 최상위 요소를 가져옵니다.
if (!stack.isEmpty()) {
return stack.peek();
}
throw new IllegalStateException();
}
int getMin()스택에서 최소 요소를 검색합니다.

O(1)각 기능에 대해 시간 복잡도가 있는 솔루션을 구현해야 합니다 .

if (!stack.isEmpty()) {
return stack.peek();
}
throw new IllegalStateException();
}

전체코드

class MinStack {
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }
    
    public void push(int val) {
        stack.push(val);
        if (minStack.isEmpty() || val <= minStack.peek()) {
            minStack.push(val);
        }
    }
    
    public void pop() {
        if (!stack.isEmpty()) {
            if (stack.peek().equals(minStack.peek())) {
                minStack.pop();
            }
            stack.pop();
        }
    }
    
    public int top() {
         if (!stack.isEmpty()) {
            return stack.peek();
        }
        throw new IllegalStateException();
    }
    
    public int getMin() {
         if (!minStack.isEmpty()) {
            return minStack.peek();
        }
        throw new IllegalStateException();
    }
}
profile
let's go invent tomorrow rather than worrying about what happened yesterday - Steven Paul Jobs

0개의 댓글