2020年4月30日 星期四

[LeetCode] 155. Min Stack 解題思路 (Easy)



這題需要製作 MinStack 這個資料結構。




LeetCode 題目連結

 

https://leetcode.com/problems/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 1:
Input
["MinStack","push","push","push","getMin","pop","top","getMin"]
[[],[-2],[0],[-3],[],[],[],[]]

Output
[null,null,null,null,-3,null,0,-2]

Explanation
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); // return -3
minStack.pop();
minStack.top();    // return 0
minStack.getMin(); // return -2

Constraints:
  • Methods poptop and getMin operations will always be called on non-empty stacks.

Accept 作法


這題利用 ArrayList 實現。


Runtime: 119 ms
Memory: 41.6 MB

Java 程式碼

  1. class MinStack {
  2. ArrayList<Integer> stack;
  3. /** initialize your data structure here. */
  4. public MinStack() {
  5. stack = new ArrayList<Integer>();
  6. }
  7. public void push(int x) {
  8. stack.add(x);
  9. }
  10. public void pop() {
  11. if(stack.isEmpty())
  12. return;
  13. stack.remove(stack.size() - 1);
  14. }
  15. public int top() {
  16. if(stack.isEmpty())
  17. return 0;
  18. return stack.get(stack.size() - 1);
  19. }
  20. public int getMin() {
  21. if(stack.isEmpty())
  22. return 0;
  23. int min = stack.get(0);
  24. for(int i = 1;i<stack.size();i++){
  25. if(min > stack.get(i)){
  26. min = stack.get(i);
  27. }
  28. }
  29. return min;
  30. }
  31. }

 

更多 LeetCode 相關資源

 

複習程式面試書籍


除了 LeetCode 練習外,我也入手了這本,題庫來自真正的面試,並非摘自教科書。它們反映出頂尖公司真正會出的題目,你可以藉此做好充分準備
需要的話可以看看,寫得很仔細。
 

書名:提升程式設計師的面試力:189道面試題目與解答



相關 LeetCode文章一律會放在 程式解題 標籤分類,歡迎持續追蹤。

沒有留言:

張貼留言