自己可以做网站服务器,域客式单页网站能申请域名吗,wordpress 小工具移动,临沂市建设安全管理网站5895. 获取单值网格的最小操作数
给你一支股票价格的数据流。数据流中每一条记录包含一个 时间戳 和该时间点股票对应的 价格 。
不巧的是#xff0c;由于股票市场内在的波动性#xff0c;股票价格记录可能不是按时间顺序到来的。某些情况下#xff0c;有的记录可能是错的…5895. 获取单值网格的最小操作数
给你一支股票价格的数据流。数据流中每一条记录包含一个 时间戳 和该时间点股票对应的 价格 。
不巧的是由于股票市场内在的波动性股票价格记录可能不是按时间顺序到来的。某些情况下有的记录可能是错的。如果两个有相同时间戳的记录出现在数据流中前一条记录视为错误记录后出现的记录 更正 前一条错误的记录。
请你设计一个算法实现
更新 股票在某一时间戳的股票价格如果有之前同一时间戳的价格这一操作将 更正 之前的错误价格。 找到当前记录里 最新股票价格 。最新股票价格 定义为时间戳最晚的股票价格。 找到当前记录里股票的 最高价格 。 找到当前记录里股票的 最低价格 。 请你实现 StockPrice 类
StockPrice() 初始化对象当前无股票价格记录。void update(int timestamp, int price) 在时间点 timestamp 更新股票价格为 price 。int current() 返回股票 最新价格 。int maximum() 返回股票 最高价格 。int minimum() 返回股票 最低价格 。
示例 1输入
[StockPrice, update, update, current, maximum, update, maximum, update, minimum]
[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]
输出
[null, null, null, 5, 10, null, 5, null, 2]解释
StockPrice stockPrice new StockPrice();
stockPrice.update(1, 10); // 时间戳为 [1] 对应的股票价格为 [10] 。
stockPrice.update(2, 5); // 时间戳为 [1,2] 对应的股票价格为 [10,5] 。
stockPrice.current(); // 返回 5 最新时间戳为 2 对应价格为 5 。
stockPrice.maximum(); // 返回 10 最高价格的时间戳为 1 价格为 10 。
stockPrice.update(1, 3); // 之前时间戳为 1 的价格错误价格更新为 3 。// 时间戳为 [1,2] 对应股票价格为 [3,5] 。
stockPrice.maximum(); // 返回 5 更正后最高价格为 5 。
stockPrice.update(4, 2); // 时间戳为 [1,2,4] 对应价格为 [3,5,2] 。
stockPrice.minimum(); // 返回 2 最低价格时间戳为 4 价格为 2 。解题思路
void update(int timestamp, int price) 在时间点 timestamp 更新股票价格为 price 。int current() 返回股票 最新价格 。int maximum() 返回股票 最高价格 。int minimum() 返回股票 最低价格 。 我们的目标是实现上述4个方法。
int current() 返回股票 最新价格。我们只需要维护两个变量最大的时间戳以及对应的价格即可而对于其他方法我们需要读取的是股票的最低以及最高价格但是update方法会更正某些时间戳的价格因此股票的最高和最低价格是动态更新的。使用一个treemap维护价格和时间戳的对应关系对于某个价格该股票可能有多个对应的时间戳利用treemap的特性我们可以在o1的时间复杂度内获取当前最大和最小价格。我们可以使用map维护每个时间戳对应的价格。而update方法就需要维护上面的两个map。通过map我们可以得到需要更新的时间戳原价是多少再通过这个价格定位到treemap里面删除该时间戳。然后再将该时间戳和价格的对应关系插入到map和treemap里面
代码 class StockPrice {//timeStamp -priceMapInteger, Integer map new HashMap();//price - timeStampsTreeMapInteger, SetInteger up new TreeMap();int curTime-1,curPrice-1;public StockPrice() {}public void update(int timestamp, int price) {if (timestampcurTime){curTimetimestamp;curPriceprice;}if(map.containsKey(timestamp)){Integer old map.get(timestamp);up.get(old).remove(timestamp);if (up.get(old).isEmpty())up.remove(old);}map.put(timestamp, price);if (!up.containsKey(price))up.put(price,new HashSet());up.get(price).add(timestamp);}public int current() {return curPrice;}public int maximum() {return up.lastKey();}public int minimum() {return up.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();*/