zoukankan      html  css  js  c++  java
  • 1475. Final Prices With a Special Discount in a Shop

    Given the array prices where prices[i] is the price of the ith item in a shop. There is a special discount for items in the shop, if you buy the ith item, then you will receive a discount equivalent to prices[j] where j is the minimum index such that j > i and prices[j] <= prices[i], otherwise, you will not receive any discount at all.

    Return an array where the ith element is the final price you will pay for the ith item of the shop considering the special discount.

    n2方法,两层for循环,对于每个i去寻找最小的j满足prices[j] <= prices[i],然后prices[i] -= prices[j]就是答案了

    on方法,维护一个单调上升的栈,遇到比栈顶更小的值的时候,就是找到最小j的时候,把栈里比price[j]价格高的都出栈,然后都分别减去这个prices[j] ,就得到了他们的最终结果,再把j入栈。重复这个过程

    class Solution(object):
        def finalPrices(self, prices):
            """
            :type prices: List[int]
            :rtype: List[int]
            """
            stack = []
            for i in range(len(prices)):
                while len(stack) != 0 and prices[stack[-1]] >= prices[i]:
                    prices[stack[-1]] -= prices[i]
                    stack.pop()
                stack.append(i)
            return prices
                    
  • 相关阅读:
    对象结构型
    对象结构型
    对象行为型模式
    定时任务(二)
    定时任务(一)
    kill端口-更新sql-添加字段
    获取ip和端口号
    List集合中的末位元素置首位
    首页报表数据展示(一)
    具体的类中包括枚举类写法
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13207231.html
Copyright © 2011-2022 走看看