【Leetcode-每日一题】股票价格波动

股票价格波动
难度:中等
【Leetcode-每日一题】股票价格波动_第1张图片
【Leetcode-每日一题】股票价格波动_第2张图片
我们可以通过哈希表(时间戳:价格)来记录映射关系,定义变量 cur 记录最大时间戳,题目中还要求需要返回最高价格和最低价格,可以用TreeMap(价格:该价格出现的次数)来记录,默认会以key作升序排序。那么通过treeMap的firstKey和lastKey方法就能分别获得最高价格和最低价格了。
代码如下:

class StockPrice {
    //key为时间戳,value为价格
    Map<Integer,Integer> map = new HashMap<>();
    //key为价格,value为该价格出现的次数
    TreeMap<Integer,Integer> treeMap = new TreeMap();
    //记录当前最大时间戳
    int cur = 0;
    
    public void update(int timestamp, int price) {
        cur = Math.max(timestamp,cur);
        if(map.containsKey(timestamp)){
            int old = map.get(timestamp);
            int cnt = treeMap.get(old);
            if(cnt == 1){
                treeMap.remove(old);
            }else{
                treeMap.put(old,treeMap.get(old)-1);
            }
        }   
        map.put(timestamp,price); 
        treeMap.put(price,treeMap.getOrDefault(price,0)+1);
    }
    
    public int current() {
        return map.get(cur);
    }
    
    public int maximum() {
        return treeMap.lastKey();
    }
    
    public int minimum() {
        return treeMap.firstKey();
    }
}

执行结果:成功
【Leetcode-每日一题】股票价格波动_第3张图片

你可能感兴趣的:(#,LeetCode-每日一题,leetcode,算法,职场和发展)