File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 113
113
- [ 20 前序中序求后序] ( #20-前序中序求后序 )
114
114
- [ 21 单链表逆置] ( #21-单链表逆置 )
115
115
- [ 22 两个字符串是否是变位词] ( #22-两个字符串是否是变位词 )
116
+ - [ 23 O(1)时间复杂度实现入栈、出栈、获得栈中最小元素、获得栈中最大元素] ( #23-O(1)时间复杂度实现入栈、出栈、获得栈中最小元素、获得栈中最大元素 )
116
117
<!-- markdown-toc end -->
117
118
118
119
# Python语言特性
@@ -1673,3 +1674,71 @@ class Anagram:
1673
1674
```
1674
1675
1675
1676
1677
+ ## 23 O(1)时间复杂度实现入栈、出栈、获得栈中最小元素、获得栈中最大元素
1678
+
1679
+ ``` python
1680
+ # 定义栈结构,根据栈的后进先出特性,增加辅助栈,来存储当前状态下数据栈中的最小、最大元素。
1681
+ class Stack (object ):
1682
+
1683
+ def __init__ (self ):
1684
+ self .data = []
1685
+ self .minValue = []
1686
+ self .maxValue = []
1687
+
1688
+ def push (self ,data ):
1689
+ self .data.append(data)
1690
+ if len (self .minValue)== 0 :
1691
+ self .minValue.append(data)
1692
+ else :
1693
+ if data <= self .minValue[- 1 ]:
1694
+ self .minValue.append(data)
1695
+ if len (self .maxValue)== 0 :
1696
+ self .maxValue.append(data)
1697
+ else :
1698
+ if data>= self .maxValue[- 1 ]:
1699
+ self .maxValue.append(data)
1700
+
1701
+ def pop (self ):
1702
+ if len (self .data)== 0 :
1703
+ return None
1704
+ else :
1705
+ temp = self .data.pop()
1706
+ if temp == self .minValue[- 1 ]:
1707
+ self .minValue.pop()
1708
+ if temp == self .maxValue[- 1 ]:
1709
+ self .maxValue.pop()
1710
+ return temp
1711
+
1712
+ def min (self ):
1713
+ if len (self .data)== 0 :
1714
+ return None
1715
+ else :
1716
+ return self .minValue[- 1 ]
1717
+
1718
+ def max (self ):
1719
+ if len (self .data)== 0 :
1720
+ return None
1721
+ else :
1722
+ return self .maxValue[- 1 ]
1723
+
1724
+ def show (self ):
1725
+ print (" stack data" )
1726
+ for data in self .data:
1727
+ print (data)
1728
+ print (" min" ,self .min())
1729
+ print (" max" ,self .max())
1730
+
1731
+ if __name__ == " __main__" :
1732
+ s = Stack()
1733
+ s.push(2 )
1734
+ s.push(1 )
1735
+ s.show()
1736
+ s.push(4 )
1737
+ s.push(3 )
1738
+ s.push(2 )
1739
+ s.show()
1740
+ s.pop()
1741
+ s.show()
1742
+ s.pop()
1743
+ s.show()
1744
+ ```
You can’t perform that action at this time.
0 commit comments