每日一题——LeetCode1475.商品折扣后的最终价格

方法一 一次遍历

对于每一个prices[i]找到在他后面且离他最近的更小值prices[j] ,prices[i]-prices[j]就是目标值,

如果不存在这样的prices[j]则直接返回prices[i]

var finalPrices = function(prices) {
    let res=[]
    for(let i=0;i<prices.length-1;i++){
        if(prices[i]-prices[i+1]>=0){
            res.push(prices[i]-prices[i+1])
        }else{
            let j=i+1
            while(j<prices.length && prices[i]-prices[j]<0){
                j++
            }
            console.log(j)
            if(j===prices.length){
                res.push(prices[i])
            }else{
                res.push(prices[i]-prices[j])
            }
        }
    }
    res.push(prices[prices.length-1])
    return res
};

消耗时间和内存情况:

方法二 单调栈

来源:力扣官方题解
链接:leetcode1475.商品折扣后的最终价格

var finalPrices = function(prices) {
    const n = prices.length;
    const ans = new Array(n).fill(0);
    const stack = [];
    for (let i = n - 1; i >= 0; i--) {
        while (stack.length && stack[stack.length - 1] > prices[i]) {
            stack.pop();
        }
        ans[i] = stack.length === 0 ? prices[i] : prices[i] - stack[stack.length - 1];
        stack.push(prices[i]);
    }
    return ans;
};  

消耗时间和内存情况:

最近更新

  1. CSS学习

    2024-02-22 23:20:02       0 阅读
  2. Unity 常用取整方法

    2024-02-22 23:20:02       1 阅读
  3. 华为机考真题 -- 攀登者1

    2024-02-22 23:20:02       1 阅读
  4. Linux内核 -- 内存管理之scatterlist结构使用

    2024-02-22 23:20:02       0 阅读
  5. 【国产开源可视化引擎Meta2d.js】数据

    2024-02-22 23:20:02       1 阅读

热门阅读

  1. windows 10 和 11 的3个杀招软件

    2024-02-22 23:20:02       39 阅读
  2. Luogu P6175 无向图的最小环问题 题解 Floyd

    2024-02-22 23:20:02       36 阅读
  3. 带你了解软件系统架构的演变

    2024-02-22 23:20:02       32 阅读
  4. jQuery的应用(二)

    2024-02-22 23:20:02       31 阅读
  5. KMP算法

    KMP算法

    2024-02-22 23:20:02      27 阅读
  6. 详解小程序配置服务器域名

    2024-02-22 23:20:02       31 阅读
  7. CSS:定位

    2024-02-22 23:20:02       29 阅读
  8. Unity3D 物理引擎的基本配置详解

    2024-02-22 23:20:02       38 阅读
  9. 设计模式的分类及Spring中用到的设计模式

    2024-02-22 23:20:02       30 阅读
  10. OkHttp 相关问题

    2024-02-22 23:20:02       33 阅读
  11. C++多态

    C++多态

    2024-02-22 23:20:02      28 阅读
  12. 2.21号qt

    2024-02-22 23:20:02       29 阅读