Skip to content

Latest commit

 

History

History
67 lines (45 loc) · 1.33 KB

20200910.md

File metadata and controls

67 lines (45 loc) · 1.33 KB

Algorithm

剑指offer-包含min函数的栈

Description

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

Solution

import java.util.Stack;

public class Solution {

    private Stack<Integer> data = new Stack<Integer>();
    private Stack<Integer> min = new Stack<Integer>();
    Integer temp = null;

    public void push(int node) {
        if (temp != null) {
            if (node <= temp) {
                temp = node;
                min.push(node);
            }
            data.push(node);
        } else {
            temp = node;
            data.push(node);
            min.push(node);
        }

    }

    public void pop() {
        int num = data.pop();
        int num2 = min.pop();
        if (num != num2) {
            min.push(num2);
        }
    }

    public int top() {
        return data.peek();
    }

    public int min() {
        return min.peek();
    }
}

Discuss

应用一个辅助栈,压的时候,如果A栈的压入比B栈压入大,B栈不压,小于等于,AB栈同时压入

出栈,如果,AB栈顶元素不等,A出,B不出。

Review

Tip

Share