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;
    }
};

为什么运行时间变长了?

相关推荐
罗西的思考7 分钟前
【Agentic RL / 强化学习 / OPD】OpenClaw-RL 源码阅读笔记 — (14)— Teacher
人工智能·笔记·深度学习·算法·机器学习
塔能物联运维17 分钟前
塔能两相液冷:600W/cm²极限能力,为下一代AI芯片预留充足散热余量
人工智能·算法·两相液冷
醉城夜风~43 分钟前
手撕 C++ string:从零实现一个简易字符串类
开发语言·c++·算法
手写码匠1 小时前
华为云Flexus+DeepSeek征文|DeepSeek+RAG知识库实战:基于Flexus X实例与Dify构建企业级智能问答系统
人工智能·深度学习·算法·aigc
zander2582 小时前
LeetCode 46. 全排列
算法·leetcode·深度优先
星恒随风2 小时前
C++ STL 详解:set 与 multiset 的使用、区间查询和算法应用
开发语言·c++·笔记·学习·算法
Lumos1862 小时前
《ESP32 物联网全栈实战-02》ESP-IDF 工程结构
算法
QN1幻化引擎3 小时前
把 意识评测做成了一场"非侵入实验":不碰生产代码,分数反而更真了
人工智能·算法·架构
冻柠檬飞冰走茶3 小时前
PTA基础编程题目集 7-17 爬动的蠕虫(C语言实现)
c语言·开发语言·数据结构·算法
会编程的土豆4 小时前
LeetCode 热题 HOT100(一):哈希表与双指针入门(Go 实现)
算法·leetcode·职场和发展