当前位置: 首页 > news >正文

leetcode1475. 商品折扣后的最终价格 【单调栈】

简单题

第一次错误做法

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

运行结果:

错误分析:入栈的是元素,如果之后出现相等的元素,则会覆盖哈希表中的值。

正确思路:

修改入栈元素为下标之后:

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遍历数组元素写法:

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

 为什么运行时间变长了?

http://www.lryc.cn/news/139454.html

相关文章:

  • macOS M1使用TensorFlow GPU加速
  • GNU-gcc编译选项-1
  • 【DEVOPS】Jenkins使用问题 - 控制台输出乱码
  • logback-spring.xml
  • 华为OD机试之报文重排序【Java源码】
  • 回归预测 | MATLAB实现BES-ELM秃鹰搜索优化算法优化极限学习机多输入单输出回归预测(多指标,多图)
  • DPU在东数西算背景下如何赋能下一代算力基础设施 中科驭数在未来网络发展大会论道
  • 2021年12月 C/C++(四级)真题解析#中国电子学会#全国青少年软件编程等级考试
  • ArcGIS Serve Windows下用户密码变更导致Server服务无法启动问题
  • React 面试题集锦
  • xargs命令解决“Argument list too long”
  • R语言中<- 的含义
  • 知识图谱Neo4j安装到实践全过程
  • 贪心算法:简单而高效的优化策略
  • 一生一芯6——ubuntu rpm软件安装
  • Python练习 函数取列表最小数
  • 五种重要的 AI 编程语言
  • 【linux】2 make/Makefile和gitee
  • db-gpt安装指南(docker版本)
  • 「Java」《深度解析Java Stream流的优雅数据处理》
  • 【云驻共创】华为云之手把手教你搭建IoT物联网应用充电桩实时监控大屏
  • Hadoop分布式计算与资源调度:打开专业江湖的魔幻之门
  • 为什么叫源表?源表是如何四象限工作的?
  • 云原生周刊:Kubernetes v1.28 正式发布 | 2023.8.21
  • Git基础——基本的 Git本地操作
  • PythonJS逆向解密——实现翻译软件+语音播报
  • gPRC与SpringBoot整合教程
  • Hadoop Yarn 配置多队列的容量调度器
  • c语言练习题28:杨氏矩阵
  • 梳理系统学习R语言1-R语言实战-使用ggplot进行高阶绘图