(6)设计一个TimeMap

一、描述

  • 设计一个TimeMap,基于key value的
  • 支持两类操作set(string key, string value, int timestamp),get(string key, int timestamp)
  • 在get(string key, int timestamp)方法中,返回一个值,满足set(string key, int timestamp_prev)  timestamp_prev <= timestamp,其中timestamp_prev为最大的timestamp_prev。

 

二、思路

要借助TreeMap。

TreeMap大概描述

  • 根据key排序的map
  • 有firstkey()接口,就是排在第一的key
  • 有floorEntry()接口,其实就是largerest key。

 

三、code

 1 package algorithm;
 2 
 3 import java.util.HashMap;
 4 import java.util.TreeMap;
 5 
 6 /**
 7  * Created by adrian.wu on 2019/2/18.
 8  */
 9 public class TimeMap {
10     private HashMap<String, TreeMap<Integer, String>> map = new HashMap<>();
11 
12     private static final String ES = "";
13 
14     public void set(String key, String value, int ts) {
15         TreeMap<Integer, String> tm = map.get(key) == null ? new TreeMap<>() : map.get(key);
16         tm.put(ts, value);
17         map.put(key, tm);
18     }
19 
20     public String get(String key, int ts){
21         if(map.get(key) == null) return ES;
22         TreeMap<Integer, String> tm = new TreeMap<>();
23         if (tm.firstKey() > ts) return ES;
24         return tm.floorEntry(ts).getValue();
25     }
26 }

 

转载于:https://www.cnblogs.com/ylxn/p/10394992.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值