首页 > 其他分享 >【栈】LeetCode 155. 最小栈

【栈】LeetCode 155. 最小栈

时间:2023-01-04 11:45:29浏览次数:66  
标签:155 val int 最小 stack new LeetCode public

题目链接

155. 最小栈

思路

让栈中的每个结点都额外存储自己入栈时的栈中最小值。这样无论何时,永远能从栈顶元素取出当前栈中的最小值。

代码

class MinStack{

    // key means the number, value means the minimal number
    Stack<Pair<Integer, Integer>> stack;

    public MinStack(){

        this.stack = new Stack<>();
    }

    public void push(int val){

        if(this.stack.empty()){
            this.stack.push(new Pair<>(val, val));
            return;
        }

        this.stack.push(new Pair<>(
			val, 
			Math.min(this.stack.peek().getValue(), val)
			));
    }

    public void pop(){

        this.stack.pop();
    }

    public int top(){

        return this.stack.peek().getKey();
    }

    public int getMin(){

        return this.stack.peek().getValue();
    }
}

标签:155,val,int,最小,stack,new,LeetCode,public
From: https://www.cnblogs.com/shixuanliu/p/17024385.html

相关文章

  • 【模拟】LeetCode 54. 螺旋矩阵
    题目链接54.螺旋矩阵思路通过维护上下左右四个边界变量来控制循环。代码classSolution{publicList<Integer>spiralOrder(int[][]matrix){intfi......
  • leetcode-645. 错误的集合
    645.错误的集合-力扣(Leetcode)又用了哈希表,又用了数学计算,看题解有个位运算看不太懂funcfindErrorNums(nums[]int)[]int{m:=make(map[int]struct{},len(nu......
  • leetcode-643. 子数组最大平均数 I
    643.子数组最大平均数I-力扣(Leetcode)滑动窗口,判断好边界条件即可funcfindMaxAverage(nums[]int,kint)float64{begin,end:=0,k-1ifend>=len(n......
  • leetcode-168-easy
    ExcelSheetColumnTitleGivenanintegercolumnNumber,returnitscorrespondingcolumntitleasitappearsinanExcelsheet.Forexample:A->1B->2C-......
  • leetcode-206-easy
    ReverseLinkedListGiventheheadofasinglylinkedlist,reversethelist,andreturnthereversedlist.Example1:Input:head=[1,2,3,4,5]Output:[5,......
  • leetcode-557-easy
    ReverseWordsinaStringIIIGivenastrings,reversetheorderofcharactersineachwordwithinasentencewhilestillpreservingwhitespaceandinitialwo......
  • leetcode-627-easy
    IslandPerimeterYouaregivenrowxcolgridrepresentingamapwheregrid[i][j]=1representslandandgrid[i][j]=0representswater.Gridcellsareconn......
  • leetcode-121-easy
    BestTimetoBuyandSellStockYouaregivenanarraypriceswhereprices[i]isthepriceofagivenstockontheithday.Youwanttomaximizeyourprofitb......
  • leetcode-441-easy
    ArrangingCoinsYouhavencoinsandyouwanttobuildastaircasewiththesecoins.Thestaircaseconsistsofkrowswheretheithrowhasexactlyicoins.Th......
  • leetcode-459-easy
    RepeatedSubstringPatternGivenastrings,checkifitcanbeconstructedbytakingasubstringofitandappendingmultiplecopiesofthesubstringtogether......