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

为什么运行时间变长了?

相关推荐
代码探秘者21 分钟前
【算法】吃透18种Java 算法快速读写模板
数据结构·数据库·python·算法·spring
2301_8166512221 分钟前
C++模块化设计原则
开发语言·c++·算法
gaozhiyong081322 分钟前
提示词的解剖学:Gemini 3.1 Pro 提示工程高级策略与国内实战
人工智能·算法·机器学习
小范自学编程42 分钟前
算法训练营Day44 - 动态规划part12
算法·动态规划
。。,……~43 分钟前
RGB-IR融合算法CDDFUSE理解+复现
算法
小刘的AI小站1 小时前
L9 Policy Gradient Method (二)
算法·机器学习·强化学习
WolfGang0073211 小时前
代码随想录算法训练营 Day21 | 回溯算法 part03
数据结构·算法
tankeven1 小时前
HJ152 取数游戏
c++·算法
程序员Shawn1 小时前
【机器学习 | 第六篇】- 机器学习
人工智能·算法·机器学习·集成学习
深邃-1 小时前
数据结构-队列
c语言·数据结构·c++·算法·html5