Wins the Offer-20. Stacks (C ++ / Java) of the min function comprising

topic:

Stack data structure definition, implement this type can be a min function smallest elements contained in the stack (should the time complexity O (1)).

analysis:

Because the subject of the request to obtain the min function smallest elements stack time complexity is O (1), where they do not traverse the method of selecting the elements within the stack.

We build a new StackMin stack, the number of elements in the StackMin stack should be consistent with the number of elements in the data stack, StackMin current top element is the smallest element in the data stack.

That is, the data onto the stack, at the same time talk about the smallest element in this case pressed into StackMin, since the minimum value will be pushed onto the stack from the beginning of the stack, each time a new element, and on StackMin the top element, and if the new element is small, new elements will be pressed, otherwise it will StackMin is pressed into the top element, when the request min, returned directly to the top element of StackMin.

program:

C++

class Solution {
public:
    void push(int value) {
        s.push(value);
        if(minStack.size() == 0)
            minStack.push(value);
        else{
            if(minStack.top() > value)
                minStack.push(value);
            else
                minStack.push(minStack.top());
        }
    }
    void pop() {
        s.pop();
        minStack.pop();
    }
    int top() {
        return s.top();
    }
    int min() {
        return minStack.top();
    }
private:
    stack<int> s;
    stack<int> minStack;
};

Java

import java.util.Stack;

public class Solution {

    
    public void push(int node) {
        sData.push(node);
        if(sMin.empty())
            sMin.push(node);
        else{
            if(node < sMin.peek())
                sMin.push(node);
            else
                sMin.push(sMin.peek());
        }
    }
    
    public void pop() {
        sData.pop();
        sMin.pop();
    }
    
    public int top() {
        return sData.peek();
    }
    
    public int min() {
        return sMin.peek();
    }
    private Stack<Integer> sData = new Stack<>();
    private Stack<Integer> sMin = new Stack<>();
}

 

Guess you like

Origin www.cnblogs.com/silentteller/p/11918609.html