1852. 最终优惠价(单调栈)
生活随笔
收集整理的這篇文章主要介紹了
1852. 最终优惠价(单调栈)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1852.最終優(yōu)惠價
中文English
一位店主需要完成一項銷售任務,他將要出售的物品排成一排。
從左側開始,店主以其全價減去位于該物品右側的第一個價格較低或價格相同的商品的價格。
如果右側沒有價格低于或等于當前商品價格的商品,則以全價出售當前商品。
你需要返回每一個物品實際售出價格。
樣例
示例 1:
輸入:
Prices = [2, 3, 1, 2, 4, 2]
輸出: [1, 2, 1, 0, 2, 2]
解釋:第0個和第1個物品右邊第一個更低的價格都是1,所以實際售價需要在全價上減去1, 第3個物品右邊第一個更低的價格是2,所以實際售價要在全價上面減去2。
示例 2:
輸入:
Prices = [1, 2, 3, 4, 5]
輸出: [1, 2, 3, 4, 5]
解釋: 每一個物品都保持原價,他們的右邊都沒有等于或者更低價格的物品
注意事項
數(shù)組 Prices 的長度范圍是: [1, 100000]
Prices[i] 的整數(shù)范圍是: [1, 1000000]
輸入測試數(shù)據(jù)(每行一個參數(shù))如何理解測試數(shù)據(jù)?
第一個版本:
class Solution:
"""
@param prices: a list of integer
@return: return the actual prices
"""
"""
大致思路:單調棧
1.從右邊開始往左邊循環(huán),依次放入棧里面,如果當前值 >= 棧右邊第一個,則減去即可。如果當前值 < 棧右邊第一個,則棧右邊第一個pop掉,一直到符合條件的時候為止
2.每次取出,寫入res里面,最終返回res
"""
def FinalDiscountedPrice(self, prices):
# write your code here
if len(prices) == 0:return 0
#初始化
res,d = [prices[-1]],[prices[-1]]
l = len(prices)
for i in range(l - 2, -1,-1):
if prices[i] >= d[0]:
res.insert(0,prices[i] - d[0])
d.insert(0,prices[i])
else:
while d != [] and prices[i] < d[0]:
d.pop(0)
if d != []:
res.insert(0,prices[i] - d[0])
else:
res.insert(0,prices[i])
d.insert(0,prices[i])
return res
注:lintcode未通過,時間復雜度問題
改版后:
class Solution:
"""
@param prices: a list of integer
@return: return the actual prices
"""
"""
大致思路:單調棧
1.從左邊開始循環(huán),如果當前價格出現(xiàn)小的,則替換,否則保持不變
"""
def FinalDiscountedPrice(self, prices):
#初始化
res,d = [_ for _ in prices], []
l = len(prices)
for i in range(l):
#后面出現(xiàn)小的,說明前面的值需要pop,res前面需要被替換了
while d != [] and prices[i] <= prices[d[-1]]:
print(d)
index = d[-1]
#前面的值需要被替換
res[index] = prices[index] - prices[i]
#pop前面大的,d [大,小 ,小,小,小]
d.pop()
d.append(i)
return res
總結
以上是生活随笔為你收集整理的1852. 最终优惠价(单调栈)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WebEx如何录制电脑内的声音
- 下一篇: 使用BOOTICE 恢复系统启动项