1. 程式人生 > >劍指 Offer - 20:包含 min 函式的棧

劍指 Offer - 20:包含 min 函式的棧

題目描述

定義棧的資料結構,請在該型別中實現一個能夠得到棧中所含最小元素的min函式(時間複雜度應為O(1))

題目連結:https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49

public class Solution {

    private int size;
    private int min = Integer.MAX_VALUE;
    private Stack<Integer> stack = new Stack<>();
    private
Integer[] elements = new Integer[10]; public void push(int node) { ensureCapacity(size+1); elements[size++] = node; if (node < min) { stack.push(node); min = node; } else { stack.push(min); } } private
void ensureCapacity(int size) { int len = elements.length; if (size > len) { int newLen = (len * 3) / 2 + 1; elements = Arrays.copyOf(elements, newLen); } } public void pop() { Integer top = top(); if (top != null) { elements[
size-1] = null; size--; stack.pop(); min = stack.peek(); } } public int top() { if (size != 0) { if (size - 1 >= 0) { return elements[size-1]; } } return (Integer) null; } public int min() { return min; } }