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

为什么运行时间变长了?

相关推荐
小当家.10519 分钟前
[LeetCode]Hot100系列.贪心总结+思想总结
算法·leetcode·职场和发展
墨雪不会编程41 分钟前
数据结构—排序算法篇二
数据结构·算法·排序算法
ShineWinsu1 小时前
对于数据结构:堆的超详细保姆级解析—上
数据结构·c++·算法·计算机·二叉树·顺序表·
im_AMBER1 小时前
Leetcode 46
c语言·c++·笔记·学习·算法·leetcode
努力学算法的蒟蒻2 小时前
day09(11.6)——leetcode面试经典150
算法·leetcode·职场和发展
2301_796512522 小时前
Rust编程学习 - 内存分配机制,如何动态大小类型和 `Sized` trait
学习·算法·rust
卿言卿语3 小时前
CC23-最长的连续元素序列长度
java·算法·哈希算法
天选之女wow3 小时前
【代码随想录算法训练营——Day60】图论——94.城市间货物运输I、95.城市间货物运输II、96.城市间货物运输III
android·算法·图论
Blossom.1183 小时前
大模型在边缘计算中的部署挑战与优化策略
人工智能·python·算法·机器学习·边缘计算·pygame·tornado
时间醉酒3 小时前
数据结构:双向链表-从原理到实战完整指南
c语言·数据结构·算法