leetcode1475. 商品折扣后的最终价格 【单调栈】

简单题

第一次错误做法

cpp 复制代码
class Solution {
public:
    vector<int> finalPrices(vector<int>& prices) {
        int n = prices.size();
        stack<int> st;
        unordered_map<int, int> mp;
        int i = 0;
        while(i != prices.size()) {
            int t = prices[i];
            if (st.empty() || t > st.top()) {
                st.push(t);
                i++;
            }
            else if (t <= st.top()) {
                int x = st.top();
                st.pop();
                mp[x] = x - t;
            }
        }
        while (!st.empty()) {
            int x = st.top();
            mp[x] = x;
            st.pop();
        }
        vector<int> ans;
        for(int i = 0; i < n; i++){
            ans.push_back(mp[prices[i]]);
        }
        return ans;
    }
};

运行结果:

错误分析:入栈的是元素,如果之后出现相等的元素,则会覆盖哈希表中的值。

正确思路:

修改入栈元素为下标之后:

cpp 复制代码
class Solution {
public:
    vector<int> finalPrices(vector<int>& prices) {
        int n = prices.size();
        stack<int> st;
        vector<int> num(n);
        int i = 0;
        while(i != prices.size()) {
            int t = prices[i];
            if (st.empty() || t > prices[st.top()]) {
                st.push(i);
                i++;
            }
            else if (t <= prices[st.top()]) {
                int x = st.top();
                st.pop();
                num[x] = prices[x] - t;
            }
        }
        // 如果栈中还有元素(数组中没有比它小的值,没得优惠,就只能付原价啦)
        while (!st.empty()) {
            int x = st.top();
            num[x] = prices[x];
            st.pop();
        }
        return num;
    }
};

for遍历数组元素写法:

cpp 复制代码
class Solution {
public:
    vector<int> finalPrices(vector<int>& prices) {
        int n = prices.size();
        vector<int> ans(n);
        stack<int> st;
        for (int i = 0; i < n; i++) {
            int t = prices[i];
            while (!st.empty() && t <= prices[st.top()]) {
                int x = st.top();
                ans[x] = prices[x] - t;
                st.pop();
            }
            while (st.empty() || t > prices[st.top()]) {
                st.push(i);
            }
        }
        while (!st.empty()) {
            int x = st.top();
            ans[x] = prices[x];
            st.pop();
        }
        return ans;
    }
};

为什么运行时间变长了?

相关推荐
鶴哥只手遮天几秒前
OpenFOAM 源码深度剖析 · 第二季-13 `fvOptions` / `fvConstraints` / `corrections`
算法·开源
鶴哥只手遮天2 分钟前
OpenFOAM 源码深度剖析 · 第二季-03 拉格朗日粒子与喷雾:`Cloud`/`parcel` 模板体系、运动积分与子模型群
算法·开源
hetao17338378 分钟前
校内场-提高组 ZYZSC-S-Round 2
c++·算法
小严不想当码农9 分钟前
icpc 亚洲区域赛补题链接整理
算法
xiaok10 分钟前
Compositor图编辑器
算法
CAD开发小慧17 分钟前
CAE软件开发:Coreform为何用ACIS处理CAD几何?
算法·架构·计算机图形学
七牛云行业应用21 分钟前
DeepSeek Harness 自定义 Skill 教程:从 SKILL.md 到可复用 Agent 工作流
算法·github
hetao173383725 分钟前
2026-10-14 hetao1733837 的刷题记录
c++·算法
罗斯83939 分钟前
Datalog与安全分析
算法·安全·网络安全
浅念-1 小时前
动态规划:线性DP——多状态DP与子数组专题笔记
c++·笔记·算法·leetcode·职场和发展·动态规划·力扣