8000 增加一道剑指offer题 · pythonpeixun/interview_python@884a4ba · GitHub
[go: up one dir, main page]

Skip to content

Commit 884a4ba

Browse files
committed
增加一道剑指offer题
1 parent f81d026 commit 884a4ba

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

Readme.md

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@
113113
- [20 前序中序求后序](#20-前序中序求后序)
114114
- [21 单链表逆置](#21-单链表逆置)
115115
- [22 两个字符串是否是变位词](#22-两个字符串是否是变位词)
116+
- [23 O(1)时间复杂度实现入栈、出栈、获得栈中最小元素、获得栈中最大元素](#23-O(1)时间复杂度实现入栈、出栈、获得栈中最小元素、获得栈中最大元素)
116117
<!-- markdown-toc end -->
117118

118119
# Python语言特性
@@ -1673,3 +1674,71 @@ class Anagram:
16731674
```
16741675

16751676

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+
```

0 commit comments

Comments
 (0)
0