LeetCode1381.设计一个支持增量操作的栈设计一个支持增量操作的栈【Medium】【Python】【栈】支持LeetCode的问题LeetCode.实现CustomStack类:CustomStack(intmaxSize)使用maxSize初始化对象,maxSize是堆栈中元素的最大数量,如果堆栈达到maxSize,则不执行任何操作。voidpush(intx)将x添加到堆栈顶部如果堆栈未达到maxSize.intpop()弹出并返回堆栈顶部,如果堆栈为空则返回-1。voidinc(intk,intval)将堆栈底部的k个元素递增val。如果堆栈中的元素少于k,则将堆栈中的所有元素递增。示例1:Input["CustomStack","push","push","pop","push","push","推”,“增量”,“增量”,“流行”,“流行”,“流行”,“流行”][[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]输出[null,null,null,2,null,null,null,null,null,103,202,201,-1]乙xplanationCustomStackcustomStack=newCustomStack(3);//堆栈为空[]customStack.push(1);//堆栈变为[1]customStack.push(2);//堆栈变为[1,2]customStack.pop();//return2-->返回栈顶2,栈变为[1]customStack.push(2);//堆栈变为[1,2]customStack.push(3);//堆栈变为[1,2,3]customStack.push(4);//堆栈仍然是[1,2,3],不要添加其他元素,因为大小是4customStack.increment(5,100);//堆栈变为[101,102,103]customStack.increment(2,100);//堆栈变为[201,202,103]customStack.pop();//return103-->返回栈顶103,栈变为[201,202]customStack.pop();//return202-->返回栈顶102,栈变为[201]customStack.pop();//return201-->返回栈顶101,栈变为[]customStack.pop();//return-1-->Stackisemptyreturn-1.Constraints:1<=maxSize<=10001<=x<=10001<=k<=10000<=val<=100每个最多调用1000次increment、push和pop的方法分别分开。请设计一个支持以下操作的栈,实现自定义栈类CustomStack:CustomStack(intmaxSize):用maxSize初始化对象,maxSize是栈中可以容纳的最大元素数,栈不支持增长到maxSize后推送操作。voidpush(intx):如果栈还没有增长到maxSize,就把x加到栈顶。intpop():返回栈顶的值,如果栈为空则返回-1。voidinc(intk,intval):栈底k个元素的值全部增加val。如果堆栈中的元素总数小于k,则堆栈中的所有元素都递增val。示例:输入:["CustomStack","push","push","pop","push","push","push","increment","increment","pop","pop","流行","流行"][[3],[1],[2],[],[2],[3],[4],[5,100],[2,100],[],[],[],[]]输出:[null,null,null,2,null,null,null,null,null,103,202,201,-1]解释:CustomStackcustomStack=newCustomStack(3);//堆栈为空[]customStack.push(1);//堆栈变为[1]customStack.push(2);//堆栈变为[1,2]customStack.pop();//return2-->returnstacktopvalue2,栈变为[1]customStack.push(2);//堆栈变为[1,2]customStack.push(3);//堆栈变为[1,2,3]customStack.push(4);//堆栈仍然是[1,2,3],不能添加其他元素使堆栈大小4customStack.increment(5,100);//堆栈变为[101,102,103]customStack.increment(2,100);//堆栈变为[201,202,103]customStack.pop();//return103-->返回栈顶值103,栈变为[201,202]customStack.pop();//返回202-->返回栈顶值202,栈变为[201]customStack.pop();//return201-->返回栈顶值201,栈变为[]customStack.pop();//return-1->栈为空,return-1Tips:1<=maxSize<=10001<=x<=10001<=k<=10000<=val<=100各方法自增、push、pop最多可以调用1000次我在堆栈上犯了一个错误。弹出的时候,记得弹出栈顶元素。你不能只是返回,你必须弹出它Python3代码classCustomStack:def__init__(self,maxSize:int):self.size=0self.maxSize=maxSizeself.customStack=[]defpush(self,x:int)->None:ifself.size
