[LeetCode]题解(python):155-Min Stack

题目来源:

  https://leetcode.com/problems/min-stack/


 

题意分析:

  实现一个小的栈,包括初始化,push,pop,top,和getMin。


 

题目思路:

  思路是用两个数组来处理。


 

代码(python):

 1 class MinStack(object):
 2     def __init__(self):
 3         """
 4         initialize your data structure here.
 5         """
 6         self.stack1 = []
 7         self.stack2 = []
 8         
 9 
10     def push(self, x):
11         """
12         :type x: int
13         :rtype: nothing
14         """
15         self.stack1.append(x)
16         if len(self.stack2) == 0 or x <= self.stack2[-1]:
17             self.stack2.append(x)
18         
19 
20     def pop(self):
21         """
22         :rtype: nothing
23         """
24         tmp = self.stack1.pop()
25         if tmp == self.stack2[-1]:
26             self.stack2.pop()
27         
28 
29     def top(self):
30         """
31         :rtype: int
32         """
33         return self.stack1[-1]
34 
35     def getMin(self):
36         """
37         :rtype: int
38         """
39         return self.stack2[-1]
40         
View Code

 

posted @ 2016-05-10 17:07  Ry_Chen  阅读(960)  评论(0编辑  收藏  举报