• 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.

    链接: http://leetcode.com/problems/min-stack/

    2/18/2017, Java

    注意!我们其实可以直接用stack不用ArrayList的!

    Integer 和int是不相等的,第14行如果是Integer x = ...那么15行永远不相等!

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

    4/16/2017

    BB电面准备

    Java Stack里没有top(),但是有peek()

     1 public class MinStack {
     2     Stack<Integer> s;
     3     Stack<Integer> ms;
     4     /** initialize your data structure here. */
     5     public MinStack() {
     6         s = new Stack<Integer>();
     7         ms = new Stack<Integer>();
     8     }
     9     
    10     public void push(int x) {
    11         s.push(x);
    12         if (ms.empty() || ms.peek() >= x) ms.push(x);
    13     }
    14     
    15     public void pop() {
    16         int t = s.peek();
    17         if (t <= ms.peek()) ms.pop();
    18         s.pop();
    19     }
    20     
    21     public int top() {
    22         return s.peek();
    23     }
    24     
    25     public int getMin() {
    26         return ms.peek();
    27     }
    28 }
  • 相关阅读:
    Freefilesync-文件夹自动同步
    考研打卡_Day077
    考研打卡_Day076
    考研打卡_Day075
    考研打卡_Day074
    考研打卡_Day073
    考研打卡_Day072
    考研打卡_Day071
    考研打卡_Day070
    考研打卡_Day069
  • 原文地址:https://www.cnblogs.com/panini/p/6414720.html
Copyright © 2020-2023  润新知