当前位置:网站首页>[simple] 155 Minimum stack

[simple] 155 Minimum stack

2022-06-12 21:52:00 Caicai 2022

subject
Code
Execution time :64 ms, In all Python3 Defeated in submission 41.59% Users of
Memory consumption :18.2 MB, In all Python3 Defeated in submission 43.94% Users of
Pass the test case :31 / 31

class MinStack:
    def __init__(self):
        self.A,self.B=[],[]

    def push(self, val: int) -> None:
        self.A.append(val)
        if not self.B or val<=self.B[-1]:
            self.B.append(val)

    def pop(self) -> None:
        if self.A.pop()==self.B[-1]:
            self.B.pop()

    def top(self) -> int:
        return self.A[-1]

    def getMin(self) -> int:
        return self.B[-1]

【 Method 2】
Execution time :60 ms, In all Python3 Defeated in submission 54.96% Users of
Memory consumption :18.9 MB, In all Python3 Defeated in submission 5.10% Users of
Pass the test case :31 / 31

class MinStack:
    def __init__(self):
        self.A=[]

    def push(self, val: int) -> None:
        if not self.A:
            self.A.append((val,val))
        else:
            self.A.append((val,min(val,self.A[-1][1])))

    def pop(self) -> None:
        self.A.pop()

    def top(self) -> int:
        return self.A[-1][0]

    def getMin(self) -> int:
        return self.A[-1][1]

【 Method 3】 Push forward
No additional auxiliary stack space
Execution time :60 ms, In all Python3 Defeated in submission 54.96% Users of
Memory consumption :18.4 MB, In all Python3 Defeated in submission 26.99% Users of
Pass the test case :31 / 31

class MinStack:
    def __init__(self):
        """ initialize your data structure here. """
        self.stack = []
        self.min_value = -1

    def push(self, x: int) -> None:
        if not self.stack:
            self.stack.append(0)
            self.min_value = x
        else:
            diff = x-self.min_value
            self.stack.append(diff)
            self.min_value = self.min_value if diff > 0 else x

    def pop(self) -> None:
        if self.stack:
            diff = self.stack.pop()
            if diff < 0:
                top = self.min_value
                self.min_value = top - diff
            else:
                top = self.min_value + diff
            return top

    def top(self) -> int:
        return self.min_value if self.stack[-1] < 0 else self.stack[-1] + self.min_value

    def getMin(self) -> int:
        return self.min_value if self.stack else -1
原网站

版权声明
本文为[Caicai 2022]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202281204317815.html