Cool Leetcode

1、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.

codes below

class MinStack {
private int size = 0;
private Node head = null;
class Node {
    int val;
    // every node contains min value at the moment it was pushed
    int min;
    Node next;
    Node(int v, int m) {val = v; min = m;}
}

public void push(int x) {
    int curMin = getMin();
    int newMin = x < curMin ? x : curMin;

    Node n = new Node(x, newMin);
    n.next = head;

    head = n;
    size++;
}

public void pop() {
    if (size <= 0)
        return;

    head = head.next;
    size--;
}

public int top() {
    if (size <= 0)
        return Integer.MAX_VALUE;

    return head.val;
}

public int getMin() {
    if (size <= 0)
        return Integer.MAX_VALUE;

    return head.min;
}}

這個使用ListNode的方法我還是沒見過的。果然腦洞大開啊!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,776評論 0 33
  • 前言 由于現在 win10系統支持原生的linux 系統(如沒有安裝可以百度win10安裝bash),所以,現在可...
    sT丶閱讀 1,345評論 0 1
  • 世界若是須彌,我們便不過是寄身在這須彌間的一粒芥子。 長久以來,我們在這虛空一般的塵世間前行。即...
    辰丨熙閱讀 211評論 1 3
  • 想為你洗衣服做余生所有的佳肴 早晨在玄關接吻傍晚并肩攝下夕陽 晚飯后賴在沙發上享受難得的休息時間 小貓在一旁的柜子...
    常樂丶閱讀 266評論 0 0
  • 本篇文章已授權微信公眾號 guolin_blog (郭霖)獨家發布 前兩天買了個Android手機(ps:之前一直...
    偽文藝大叔閱讀 3,345評論 3 20