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

为什么运行时间变长了?

相关推荐
火车叼位8 分钟前
初中生也能懂的贝叶斯定理:拆解一个改变世界的公式
人工智能·数学·算法
ChoSeitaku11 分钟前
NO.66十六届蓝桥杯备战|基础算法-贪心-区间问题|凌乱的yyy|Rader Installation|Sunscreen|牛栏预定(C++)
c++·算法·蓝桥杯
用手码出世界17 分钟前
二叉树——队列bfs专题
数据结构·算法·宽度优先
OneQ66626 分钟前
C++自学笔记---指针在数组遍历中的应用
c++·笔记·算法
EnigmaCoder28 分钟前
蓝桥杯刷题周计划(第四周)
c++·算法·蓝桥杯
绿水毛怪.30 分钟前
蓝桥杯基础算法-字符串与集合
算法·职场和发展·蓝桥杯
丶Darling.38 分钟前
26考研 | 王道 | 数据结构 | 第五章 树
数据结构·考研
悄悄敲敲敲1 小时前
C++第14届蓝桥杯b组学习笔记
c++·学习·算法·蓝桥杯
佚明zj2 小时前
[ISP 3A ] AE的常用算法分析
算法·计算机视觉·接口隔离原则
代码AC不AC2 小时前
【数据结构】堆
c语言·数据结构·学习··深度剖析