Leetcode 155. Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

  • push(x) -- Push element x onto stack.
  • pop() -- Removes the element on top of the stack.
  • top() -- Get the top element.
  • getMin() -- Retrieve the minimum element in the stack.

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

 思路:用两个stack。一个用于维护最小值。例如push [10, 5, 6, 3, 1, 9, 6, 4]。minStack = [10, 5, 3, 1]。

如果stack[-1]不等于minStack[-1],我们只要pop stack就可以,不用管minStack。

 1 class MinStack(object):
 2 
 3     def __init__(self):
 4         """
 5         initialize your data structure here.
 6         """
 7         self.stack = []
 8         self.minStack = []
 9 
10     def push(self, x):
11         """
12         :type x: int
13         :rtype: void
14         """
15         self.stack.append(x)
16         if not self.minStack or x <= self.minStack[-1]:
17             self.minStack.append(x)
18 
19     def pop(self):
20         """
21         :rtype: void
22         """
23         if self.stack[-1] == self.minStack[-1]:
24             self.minStack.pop()
25         return self.stack.pop()
26 
27 
28     def top(self):
29         """
30         :rtype: int
31         """
32         return self.stack[-1]
33     
34     def getMin(self):
35         """
36         :rtype: int
37         """
38         return self.minStack[-1]
39         
40 
41 # Your MinStack object will be instantiated and called as such:
42 # obj = MinStack()
43 # obj.push(x)
44 # obj.pop()
45 # param_3 = obj.top()
46 # param_4 = obj.getMin()

 

posted @ 2017-02-18 12:50  lettuan  阅读(104)  评论(0编辑  收藏  举报