剑指offer 21题 【举例让抽象具体化】包含min函数的栈

来源:互联网 发布:曲阜问政网络平台 编辑:程序博客网 时间:2024/05/16 04:06

题目描述

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
牛客传送门:点击打开链接




思路很清晰,写代码时注意细节。

public class MinStack {    int[] value = new int[100];    int[] minValue = new int[100];    int length = 100; // 数组长度    int count = 0;    // 当前元素个数        public void push(int node) {        if(count == length){            length+=100;            int[] temp = new int[length];            int[] tempMin = new int[length];            for(int i=0;i<length-100;i++){                temp[i] = value[i];                tempMin[i] = minValue[i];            }            value = temp;            minValue = tempMin;        }        value[count] = node;        minValue[count] = count > 0 ? Math.min(minValue[count-1], node) : node;        count++;    }        public void pop() {        if(count>0)            count--;    }        public int top() {        if(count >0)            return value[count-1];        return 0;    }        public int min() {        if(count >0)            return minValue[count-1];        return 0;    }}


0 0
原创粉丝点击