首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >树图理解问题的价值

树图理解问题的价值
EN

Stack Overflow用户
提问于 2022-03-09 16:03:48
回答 1查看 39关注 0票数 0

我正在处理一个密码问题。并在讨论部分找到了解决方案。

问题- https://leetcode.com/problems/stock-price-fluctuation/

解决方案-

代码语言:javascript
复制
class StockPrice {
    HashMap<Integer, Integer> hm; //timestamp,price
    TreeMap<Integer, Integer> tm; //price, frequency
    int current;
    
    public StockPrice() {
        
        hm = new HashMap<>();
        tm = new TreeMap<>();
        current = 0;

    }
    
    public void update(int timestamp, int price) {
        
        //check whether latest timestamp or current timestamp is larger...
        current = Math.max(current, timestamp); //if timesatamp already present
        if(hm.containsKey(timestamp))
        {
            
            int oldprice=hm.get(timestamp);

           if(tm.get(oldprice)==1){
               tm.remove(oldprice); // 
           }
            else{
                tm.put(oldprice, tm.get(oldprice)-1); 
                
            }
        }
        //update new price in hm
        hm.put(timestamp, price);
        //update new frequency of new price in treemap
        tm.put (price, tm.getOrDefault(price,0)+1);
        
    }
    
    public int current() {
    return hm.get(current);
    }
    
    public int maximum() {
        return tm.lastKey();
    }
    
    public int minimum() {
        return tm.firstKey();
        
    }
}

但我不明白以下几点。如果有人能解释这将是很棒的

  1. tm.put(oldprice, tm.get(oldprice)-1);

  1. tm.put (price, tm.getOrDefault(price,0)+1);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-10 08:36:12

为了解决这个问题,你需要知道股票以特定价格交易的频率。

举个例子:

  • 在时间戳1换10,时间戳2换5。现在的最高价格是10。(
  • 有1次交易,1次交易,5次更新为3 ),现在最高价格是5。(有3次交易,5次交易)

另一个例子是:

  • 在时间戳1换10,时间戳2换5,时间戳3换10。最高价格也是10。( 10有两种交易,1种是5)
  • 时间戳1的价格被更新为3。现在最高价格仍然是10(因为时间戳3的交易)。(一次交易10次,1次交易3次,1次交易5次

)

使用

代码语言:javascript
复制
    tm.put (price, tm.getOrDefault(price,0)+1);

值得注意的是,在一个特定的价格下还发生了一次贸易。

当旧的交易被更新时,

代码语言:javascript
复制
    if (tm.get(oldprice)==1) {
        tm.remove(oldprice); // 
    } else {
        tm.put(oldprice, tm.get(oldprice)-1); 
    }

要么删除旧价格的条目(如果该价格只有一个交易),要么注意到该价格有一个交易低于该价格。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71412352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档