2034.股票价格波动

题目

2034.股票价格波动

题目大意

给你一支股票价格的数据流。数据流中每一条记录包含一个 时间戳 和该时间点股票对应的 价格

不巧的是,由于股票市场内在的波动性,股票价格记录可能不是按时间顺序到来的。某些情况下,有的记录可能是错的。如果两个有相同时间戳的记录出现在数据流中,前一条记录视为错误记录,后出现的记录 更正 前一条错误的记录。

请你设计一个算法,实现:

  • 更新 股票在某一时间戳的股票价格,如果有之前同一时间戳的价格,这一操作将 更正 之前的错误价格。
  • 找到当前记录里 最新股票价格最新股票价格 定义为时间戳最晚的股票价格。
  • 找到当前记录里股票的 最高价格
  • 找到当前记录里股票的 最低价格

请你实现 StockPrice 类:

  • StockPrice() 初始化对象,当前无股票价格记录。
  • void update(int timestamp, int price) 在时间点 timestamp 更新股票价格为 price
  • int current() 返回股票 最新价格
  • int maximum() 返回股票 最高价格
  • int minimum() 返回股票 最低价格

样例

image-20220123163235460

数据规模

image-20220123163244353

思路

c + + c++ c++中有两个关联容器,第一种是 m a p map map,内部是按照 k e y key key排序的,第二种是 u n o r d e r e d _ m a p unordered\_map unordered_map,容器内部是无序的,使用 h a s h hash hash组织内容的。

考虑使用 m a p < i n t , i n t > map<int,int> map<int,int> m u l t i s e t < i n t > multiset<int> multiset<int>。对于 m a p < i n t , i n t > map<int,int> map<int,int>来讲,它默认以 k e y key key为关键字进行排序;对于 m u l t i s t e < i n t > multiste<int> multiste<int>来讲,它默认按储存的值进行从小到大的排序。

定义map<int,int>t来存储时间戳对应的股票价格 。如果要返回最新的股票价格,可以直接返回t.rbegin()->second

定义multiset<int>p来存储所有的股票价格,它默认从小到大排序,所以最高价格为*p.begin(),最低价格为*p.rbegin()。注意在修改价格的时候,需要删除原来的价格,然后添加新的价格。

代码

class StockPrice {
public:
    map<int,int>t;
    multiset<int>p;
    StockPrice() {
        t.clear();
        p.clear();
    }
    void update(int timestamp, int price) {
        if(t.count(timestamp)){
            p.erase(p.find(t[timestamp]));
        }
        p.insert(price);
        t[timestamp]=price;
    }  
    int current() {
        return t.rbegin()->second;
    }
    
    int maximum() {
        return *p.rbegin();
    }
    
    int minimum() {
        return *p.begin();
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Phoenix_ZengHao

创作不易,能否打赏一瓶饮料?

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值