zoukankan      html  css  js  c++  java
  • 实现带时间标的哈希表

    Add a third dimension of time to a hashmap , so ur hashmap will look something like this - HashMap<K, t, V> where t is a float value. Implement the get and put methods to this map. The get method should be something like - map.get(K,t) which should give us the value. If t does not exists then map should return the closest t' such that t' is smaller than t. For example, if map contains (K,1,V1) and (K,2,V2) and the user does a get(k,1.5) then the output should be v1 as 1 is the next smallest number to 1.5

    Uber, Google 

    解法:用HashMap记录key和TreeMap,TreeMap记录Time和Value,之所以用TreeMap是因为当没有这个时间时找到比给的时间小中的最大的。

    floorkey method is used to return the greatest key less than or equal to the given key, or null if there is no such key.

    Java:

    public class TimeHashMap<Key, Time, Value> {
    
      private HashMap<Key, TreeMap<Time, Value>> map = new HashMap<Key, TreeMap<Time, Value>>();
    
      public Value get(Key key, Time time) {
        final TreeMap<Time, Value> redBlackBST = map.get(key);
        if (redBlackBST == null) return null;
        final Time floorKey = redBlackBST.floorKey(time);
        return floorKey == null ? null : redBlackBST.get(floorKey);
      }
    
      public void put(Key key, Time time, Value value) {
        if (!map.containsKey(key)) {
          map.put(key, new TreeMap<Time, Value>());
        }
        map.get(key).put(time, value);
      }
    
      public static void main(String args[]){
        TimeHashMap<String, Double, String> data = new TimeHashMap<String, Double, String>();
        data.put("K",1.0,"K1");
        data.put("K",2.0,"K2");
        System.out.println(data.get("K",0.9));
        System.out.println(data.get("K",1.0));
        System.out.println(data.get("K",1.5));
        System.out.println(data.get("K",2.0));
        System.out.println(data.get("K",2.2));
      }
    }
    

      

  • 相关阅读:
    JavaScript 初学者应知的 24 条最佳实践
    利用函数的惰性载入提高 javascript 代码性能
    Android多线程研究(9)——线程锁Lock
    Android多线程研究(8)——Java5中Futrue获取线程返回结果
    MySQL 5.6初始配置调优
    asp.net文件夹上传下载组件
    java文件夹上传下载组件
    web文件上传下载组件
    jsp文件上传下载组件
    flash文件上传下载组件
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9684296.html
Copyright © 2011-2022 走看看