实现带时间标的哈希表

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));
  }
}

  

 

 

转载于:https://www.cnblogs.com/lightwindy/p/9684296.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值