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

为什么运行时间变长了?

相关推荐
神明不懂浪漫3 分钟前
【第四章】索引——B+树、回表,加快数据库的查找能力的利器
开发语言·数据结构·数据库·经验分享·笔记·b树
LuminousCPP1 小时前
数据结构 - 排序(二):快速排序从错误初版到优化版|双指针划分 + 三数取中 + 小区间插入优化
c语言·数据结构·笔记·算法·排序算法
hansang_IR1 小时前
【题解】P9753 [CSP-S 2023] 消消乐
数据结构·c++·算法
shehuiyuelaiyuehao1 小时前
算法40,模拟运算,替换所有的问号
数据结构·算法·leetcode
用户204937554951 小时前
从“能识别”到“稳定识别”:离线ASR在真实会议场景中的问题与工程优化实践
算法
YSL0701242 小时前
OpenCode保姆级安装教程
数据结构
鹿角片ljp2 小时前
LeetCode 148:排序链表|归并排序、快慢指针找左中点与链表断开
算法
LabVIEW开发2 小时前
LabVIEW字符串特殊字符检测兼容
算法·labview·labview知识·labview功能·labview程序
晴天的雨.9923 小时前
[C++算法]快乐数
数据结构·c++·算法
孤狼warrior3 小时前
SCTR 五次失败的安全 BN 路由器
人工智能·python·深度学习·算法·安全·yolo