一、题目

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. MinStack minStack = new MinStack();
  2. minStack.push(-2);
  3. minStack.push(0);
  4. minStack.push(-3);
  5. minStack.getMin(); --> Returns -3.
  6. minStack.pop();
  7. minStack.top(); --> Returns 0.
  8. minStack.getMin(); --> Returns -2.

二、思路&心得

  题意大致就是模拟栈的实现,这题比较出戏的一点就是要求在线性时间内获得栈中的最小值。一共有两个方法,都是比较巧妙的。

方法一:

  • 维护两个自己构造的”栈“对象, 在这里为两个数组stack和sm,其中sm的栈顶为当前stack中最小元素;
  • 在push时要判断sm是否为空,如果为空或者非空但是栈顶元素大于等于插入值的 需要在sm中插入x;
  • 在pop时,s的元素被删除了,那么sm中的也应该被删除;
  • 通过这些操作维护sm能很巧妙在O(1)复杂度得到最小值。

方法二:

  • 栈中的每个对象为(x, y),其中x为元素值,y为当前对象处于栈顶时,栈中的最小元素;
  • 在push的时候,令y为要push的值x和当前栈中最小值两个中的最小值;
  • 在top和getMin方法中,直接根据需要返回栈顶的第一个或第二个元素即可。

三、代码

方法一:

  1. class MinStack(object):
  2. def __init__(self):
  3. """
  4. initialize your data structure here.
  5. """
  6. self.stack = []
  7. self.sm = []
  8. def push(self, x):
  9. """
  10. :type x: int
  11. :rtype: void
  12. """
  13. self.stack.append(x)
  14. if not self.sm or self.sm[-1] >= x:
  15. self.sm.append(x)
  16. def pop(self):
  17. """
  18. :rtype: void
  19. """
  20. if self.sm[-1] == self.stack[-1]:
  21. self.sm.pop()
  22. self.stack.pop()
  23. def top(self):
  24. """
  25. :rtype: int
  26. """
  27. return self.stack[-1]
  28. def getMin(self):
  29. """
  30. :rtype: int
  31. """
  32. return self.sm[-1]

方法二:

  1. class MinStack(object):
  2. def __init__(self):
  3. """
  4. initialize your data structure here.
  5. """
  6. self.stack = []
  7. def push(self, x):
  8. """
  9. :type x: int
  10. :rtype: void
  11. """
  12. if not (self.stack):
  13. self.stack.append((x,x))
  14. else:
  15. self.stack.append((x, min(x, self.stack[-1][1])))
  16. def pop(self):
  17. """
  18. :rtype: void
  19. """
  20. if self.stack:
  21. self.stack.pop()
  22. else:
  23. return None
  24. def top(self):
  25. """
  26. :rtype: int
  27. """
  28. if self.stack:
  29. return self.stack[-1][0]
  30. return None
  31. def getMin(self):
  32. """
  33. :rtype: int
  34. """
  35. if self.stack:
  36. return self.stack[-1][1]
  37. return None

【Python】LeetCode-155的更多相关文章

  1. 【python】Leetcode每日一题-寻找旋转排序数组中的最小元素

    [python]Leetcode每日一题-寻找旋转排序数组中的最小元素 [题目描述] 已知一个长度为 n 的数组,预先按照升序排列,经由 1 到 n 次 旋转 后,得到输入数组.例如,原数组nums ...

  2. 【python】Leetcode每日一题-删除有序数组中的重复项

    [python]Leetcode每日一题-删除有序数组中的重复项 [题目描述] 给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 最多出现一次 ,返回删除后数组的新长度. 不要 ...

  3. 【python】Leetcode每日一题-存在重复元素3

    [python]Leetcode每日一题-存在重复元素3 [题目描述] 给你一个整数数组 nums 和两个整数 k 和 t .请你判断是否存在 两个不同下标 i 和 j,使得 abs(nums[i] ...

  4. 【python】Leetcode每日一题-扰乱字符串

    [python]Leetcode每日一题-扰乱字符串 [题目描述] 使用下面描述的算法可以扰乱字符串 s 得到字符串 t : 如果字符串的长度为 1 ,算法停止 如果字符串的长度 > 1 ,执行 ...

  5. 【python】Leetcode每日一题-前缀树(Trie)

    [python]Leetcode每日一题-前缀树(Trie) [题目描述] Trie(发音类似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的 ...

  6. 【python】Leetcode每日一题-打家劫舍2

    [python]Leetcode每日一题-打家劫舍2 [题目描述] 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金.这个地方所有的房屋都 围成一圈 ,这意味着第一个房屋和最后一个房屋 ...

  7. 【python】Leetcode每日一题-二叉搜索树节点最小距离

    [python]Leetcode每日一题-二叉搜索树节点最小距离 [题目描述] 给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 . 示例1: 输入:root = [4 ...

  8. 【python】Leetcode每日一题-最大数

    [python]Leetcode每日一题-最大数 [题目描述] 给定一组非负整数 nums,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数. 注意:输出结果可能非常大,所以你需要返回一个 ...

  9. 【python】Leetcode每日一题-丑数2

    [python]Leetcode每日一题-丑数2 [题目描述] 给你一个整数 n ,请你找出并返回第 n 个 丑数 . 丑数 就是只包含质因数 2.3 和/或 5 的正整数. 示例1: 输入:n = ...

  10. 【python】Leetcode每日一题-丑数

    [python]Leetcode每日一题-丑数 [题目描述] 给你一个整数 n ,请你判断 n 是否为 丑数 .如果是,返回 true :否则,返回 false . 丑数 就是只包含质因数 2.3 和 ...

随机推荐

  1. 如何修改macbook的MAC地址

    修改命令 sudo ifconfig en0 ether xx:xx:xx:xx:xx:xx 查看 ifconfig en0 | grep ether 随机生产一个MAC地址 openssl rand ...

  2. delphi7 TRichView 安装

    下载: 链接: https://pan.baidu.com/s/1gfMYeGF 密码: 45bn 打开目录:E:\Delphi7\TRichView.v.16.10.3 ScaleRichView. ...

  3. android6.0系统Healthd分析及低电量自动关机流程

    系统平台:android6.0概述Healthd是android4.4之后提出来的一种中介模型,该模型向下监听来自底层的电池事件,向上传递电池数据信息给Framework层的BatteryServic ...

  4. 天天沉迷于皇上本宫的都是sb

    天天沉迷于皇上.本宫.奴才.太后的都是sb,时不时还要被某王和某平民的爱情感动的落泪.这是病,要治,最有效的治疗方法是38度的夏天去搬砖. 拍这些电视的人真不傻,知道真sb多,这种电视剧才能爆款.

  5. django-groundwork

    我的环境是windows7 + python34 + django1.8 下面两篇文章提到了django的scaffold,感觉是一个挺不错的功能: Django实战(3):Django也可以有sca ...

  6. 径向基(RBF)神经网络python实现

    from numpy import array, append, vstack, transpose, reshape, \ dot, true_divide, mean, exp, sqrt, lo ...

  7. wannafly 17D 01序列2

    水题. 假设有两个二进制数a,b,c=a+b(a,b拼接起来) 那么显然如果b长度为偶数\(c\mod 3=(b\mod 3+a\mod 3)\mod 3\) 否则\(c\mod 3=(b\mod 3 ...

  8. JS字符串补全方法padStart()和padEnd()

    背景: var t = new Date().getMonth() + 1; // t ===> 7,没有0,怎么展示成下面的样子? // 2018-07-23 解决上述问题的一个思路: // ...

  9. 细说 Django — web 前后端分离

    一.所谓的前后端分离 1.渊源 前端发展史 2.特点 前端:负责 View 和 Controller 层 后端:只负责 Model 层,业务处理/数据等 3.优缺点 优点:解耦,解放前端,职责明确 缺 ...

  10. webpack vue app.js自动注入页面.为app.js增加随机参数

    node_modules/html-webpack-plugin/index.js 搜索 postProcessHtml 修改代码增加如下: if (assetTags && asse ...