持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第16天,点击查看活动详情
LeetCode每日一题打卡专栏正式启动!不出意外将日更LeetCode的每日一题,敬请期待。
2034:股票价格波动
题意
给你一支股票价格的数据流。数据流中每一条记录包含一个 时间戳 和该时间点股票对应的 价格 。
不巧的是,由于股票市场内在的波动性,股票价格记录可能不是按时间顺序到来的。某些情况下,有的记录可能是错的。如果两个有相同时间戳的记录出现在数据流中,前一条记录视为错误记录,后出现的记录 更正 前一条错误的记录。
请你设计一个算法,实现:
- 更新 股票在某一时间戳的股票价格,如果有之前同一时间戳的价格,这一操作将 更正 之前的错误价格。
- 找到当前记录里 最新股票价格 。最新股票价格 定义为时间戳最晚的股票价格。
- 找到当前记录里股票的 最高价格 。
- 找到当前记录里股票的 最低价格 。
请你实现 StockPrice 类:
- StockPrice() 初始化对象,当前无股票价格记录。
- void update(int timestamp, int price) 在时间点 timestamp 更新股票价格为 price 。
- int current() 返回股票 最新价格 。
- int maximum() 返回股票 最高价格 。
- int minimum() 返回股票 最低价格 。
提示:
- update,current,maximum 和 minimum 总 调用次数不超过 。
- current,maximum 和 minimum 被调用时,update 操作 至少 已经被调用过 一次 。
题解:数据结构
直接数据结构模拟,具体看代码。(全依靠于高级程序设计语言实现,感觉题目没意思)
C++代码:
class StockPrice {
public:
int cur,curPrice; //记录最近的时间戳以及对应的价格
multiset<int> set; //价格从小到大排序
map<int,int> mp; //记录各个时间戳和价格
StockPrice() {
set.clear();mp.clear();cur=0;
}
void update(int timestamp, int price) {
if(cur<=timestamp){
cur=timestamp;curPrice=price;
}
int pre_price=mp[timestamp];
mp[timestamp]=price;
if(pre_price>0){
auto it=set.find(pre_price);
if(it!=set.end()){
set.erase(it);
}
}
set.emplace(price);
}
int current() {
return curPrice;
}
int maximum() {
return *set.rbegin();
}
int minimum() {
return *set.begin();
}
};
/**
* Your StockPrice object will be instantiated and called as such:
* StockPrice* obj = new StockPrice();
* obj->update(timestamp,price);
* int param_2 = obj->current();
* int param_3 = obj->maximum();
* int param_4 = obj->minimum();
*/
Java代码:
class StockPrice {
int cur; // 记录最近的时间戳
int curPrice;
Map<Integer, Integer> mp1;
TreeMap<Integer, Integer> mp2;
public StockPrice() {
mp1 = new HashMap<Integer, Integer>();
mp2 = new TreeMap<Integer, Integer>();
cur=0;
}
public void update(int timestamp, int price) {
if (cur <= timestamp) {
cur = timestamp;
curPrice = price;
}
int pre_price = 0;
if (mp1.containsKey(timestamp))
pre_price = mp1.get(timestamp);
mp1.put(timestamp, price);
if (pre_price > 0) {
mp2.put(pre_price, mp2.get(pre_price) - 1);
if (mp2.get(pre_price) == 0) {
mp2.remove(pre_price);
}
}
mp2.put(price, mp2.getOrDefault(price, 0) + 1);
}
public int current() {
return curPrice;
}
public int maximum() {
return mp2.lastKey();
}
public int minimum() {
return mp2.firstKey();
}
}
/**
* Your StockPrice object will be instantiated and called as such: StockPrice
* obj = new StockPrice(); obj.update(timestamp,price); int param_2 =
* obj.current(); int param_3 = obj.maximum(); int param_4 = obj.minimum();
*/