题解 | #包含min函数的栈#

包含min函数的栈

http://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49

思路很好:使用一个最小值的栈来保存当前的最小值,并且使其长度和保存所有数据的栈的长度一致,这样可以确保数据的出栈不会导致当前最小值的过时。 特别是,push()方法可以保证Little的栈顶元素是Total中所有元素的最小元素。 若新入栈的数据比当前最小的小,那么让它作为Little的栈顶元素,并一直入栈,直到遇到比它小的元素。 Little中的占位和随着Total的出栈顶,也进行出栈顶的现象,也可以及时更新当前最小,即,当Little当前的栈顶元素在Total中出栈时,最小元素也实现了更新。

import java.util.Stack;

public class Solution {
    
    private Stack<Integer> Total = new Stack<Integer>();
    private Stack<Integer> Little = new Stack<Integer>();
    
    public void push(int node) {
        Total.push(node);
        if (Little.empty()) {
            Little.push(node);
        } else {
            if (node <= Little.peek()) {
                Little.push(node);
            } else {
                Little.push(Little.peek()); // 起到一个占位的作用
            }
        }
    }
    
    public void pop() {
        Total.pop();
        Little.pop();
    }
    
    public int top() {
        return Total.peek();
    }
    
    public int min() {
        return Little.peek();
    }

    /*private int[] temp = new int[100];
    private int N = 0;
    
    public boolean isEmpty() {
        return N == 0;
    }
    
    public int[] resize(int capacity) {
        int[] temp = new int[capacity];
        
        return temp;
    } 
    
    public void push(int node) {
        if (N == temp.length)
            resize(2 * temp.length);
        temp[N++] = node;
    }
    
    public void pop() {
        N--;
        if (N > 0 && N < temp.length / 4)
            resize(temp.length / 2);
    }
    
    public int top() {
        return temp[N - 1];
    }
    
    public int min() {
        int min = temp[0];
        for (int i = 1; i < N; i++) {
            if (temp[i] < min)
                min = temp[i];
        }
        return min;
    }*/
}

import java.util.Stack;

public class Solution {

    private int[] temp = new int[100];
    private int N = 0;
    
    public boolean isEmpty() {
        return N == 0;
    }
    
    public int[] resize(int capacity) {
        int[] temp = new int[capacity];
        
        return temp;
    } 
    
    public void push(int node) {
        if (N == temp.length)
            resize(2 * temp.length);
        temp[N++] = node;
    }
    
    public void pop() {
        N--;
        if (N > 0 && N < temp.length / 4)
            resize(temp.length / 2);
    }
    
    public int top() {
        return temp[N - 1];
    }
    
    public int min() {
        int min = temp[0];
        for (int i = 1; i < N; i++) {
            if (temp[i] < min)
                min = temp[i];
        }
        return min;
    }
}
全部评论

相关推荐

仁者伍敌:难怪小公司那么挑剔,让你们这些大佬把位置拿了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 13:05
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务