zoukankan      html  css  js  c++  java
  • 1852. 最终优惠价(单调栈)

    1852. 最终优惠价

    中文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]
    解释: 每一个物品都保持原价,他们的右边都没有等于或者更低价格的物品
    

    注意事项

    • 数组 Prices 的长度范围是: [1, 100000]
    • Prices[i] 的整数范围是: [1, 1000000]
     
     
    输入测试数据 (每行一个参数)如何理解测试数据?

     第一个版本:

    class Solution:
        """
        @param prices: a list of integer
        @return: return the actual prices
        """
        """
        大致思路:单调栈
        1.从右边开始往左边循环,依次放入栈里面,如果当前值 >= 栈右边第一个,则减去即可。如果当前值 < 栈右边第一个,则栈右边第一个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.从左边开始循环,如果当前价格出现小的,则替换,否则保持不变
        """
        def FinalDiscountedPrice(self, prices):
            #初始化
            res,d = [_ for _ in prices], []
    
            l = len(prices)
            for i in range(l):
                #后面出现小的,说明前面的值需要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 
  • 相关阅读:
    高仿IOS下拉刷新的粘虫效果
    CSDN无耻,亿赛通无耻
    2014年10月Android面试总结
    HttpClient和HttpURLConnection的使用和区别(下)
    HttpClient和HttpURLConnection的使用和区别(上)
    Gson简单使用
    Android PowerImageView实现,可以播放动画的强大ImageView
    Android访问网络,使用HttpURLConnection还是HttpClient?
    自定义android ProgressDialog
    NPOI导Excel样式设置
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/13113813.html
Copyright © 2011-2022 走看看