LeetCode初級(jí)算法--設(shè)計(jì)問題02:最小棧
一、引子
這是由LeetCode官方推出的的經(jīng)典面試題目清單~
這個(gè)模塊對(duì)應(yīng)的是探索的初級(jí)算法~旨在幫助入門算法。我們第一遍刷的是leetcode推薦的題目。
二、題目
設(shè)計(jì)一個(gè)支持 push,pop,top 操作,并能在常數(shù)時(shí)間內(nèi)檢索到最小元素的棧。
- push(x) -- 將元素 x 推入棧中。
- pop() -- 刪除棧頂?shù)脑亍?/li>
- top() -- 獲取棧頂元素。
- getMin() -- 檢索棧中的最小元素。
示例:
MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin(); --> 返回 -3.
minStack.pop();
minStack.top(); --> 返回 0.
minStack.getMin(); --> 返回 -2.
1、思路
第一種方法:
用列表模擬棧,push、pop、top和getMin分別對(duì)應(yīng)list.append()、list.pop()、list[-1]和min()操作
第二種方法:
引入minStack列表存放最小值
2、編程實(shí)現(xiàn)
第一種方法:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.l = []
def push(self, x):
"""
:type x: int
:rtype: None
"""
if x is None:
pass
else:
self.l.append(x)
def pop(self):
"""
:rtype: None
"""
if self.l is None:
return 'error'
else:
self.l.pop(-1)
def top(self):
"""
:rtype: int
"""
if self.l is None:
return 'error'
else:
return self.l[-1]
def getMin(self):
"""
:rtype: int
"""
if self.l is None:
return 'error'
else:
return min(self.l)
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
第二種方法:
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = [] #存放所有元素
self.minStack = []#存放每一次壓入數(shù)據(jù)時(shí),棧中的最小值(如果壓入數(shù)據(jù)的值大于棧中的最小值就不需要重復(fù)壓入最小值,小于或者等于棧中最小值則需要壓入)
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if not self.minStack or self.minStack[-1]>=x:
self.minStack.append(x)
def pop(self): #移除棧頂元素時(shí),判斷是否移除棧中最小值
"""
:rtype: void
"""
if self.minStack[-1]==self.stack[-1]:
del self.minStack[-1]
self.stack.pop()
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.minStack[-1]
本文由博客一文多發(fā)平臺(tái) OpenWrite 發(fā)布!
審核編輯 黃昊宇
-
人工智能
+關(guān)注
關(guān)注
1807文章
49029瀏覽量
249655 -
機(jī)器學(xué)習(xí)
+關(guān)注
關(guān)注
66文章
8503瀏覽量
134648 -
深度學(xué)習(xí)
+關(guān)注
關(guān)注
73文章
5561瀏覽量
122806 -
leetcode
+關(guān)注
關(guān)注
0文章
20瀏覽量
2453
發(fā)布評(píng)論請(qǐng)先 登錄
RISC-V架構(gòu)下AI融合算力及其軟件棧實(shí)踐

基于APM32F407如何制作I2C EEPROM(AT24C02型號(hào))的MDK-Keil下載算法

深入淺出解析低功耗藍(lán)牙協(xié)議棧

74VHC02;74VHCT02四路2輸入或非門規(guī)格書

自動(dòng)駕駛?cè)?b class='flag-5'>棧自研可行嗎?
曙光云開啟全棧智能時(shí)代
常見的lvs負(fù)載均衡算法
λ-IO:存儲(chǔ)計(jì)算下的IO棧設(shè)計(jì)

TPS62A02和TPS62A02A降壓轉(zhuǎn)換器評(píng)估模塊用戶指南

RVBacktrace RISC-V極簡(jiǎn)棧回溯組件

明緯電源DETN02-N系列非穩(wěn)壓轉(zhuǎn)換器產(chǎn)品概述

Linux網(wǎng)絡(luò)協(xié)議棧的實(shí)現(xiàn)

評(píng)論