Created
March 18, 2017 05:10
-
-
Save bookybooky/a4161cdd3fdd6200cd33d06014a68019 to your computer and use it in GitHub Desktop.
Implement TimeTravelingHashTable的get和insert方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* TimeTravelingHashTable | |
* insert(key, value, timestamp) | |
* get(key, timestamp) | |
* get(key) // returns value associated with key at latest time | |
* | |
* insert("k1", "v1", 10) | |
* get("k1") // returns "v1" | |
* get("k1", 11) // returns "v1" | |
* insert("k1", "v2", 20) | |
* get("k1", 15) // returns "v1" | |
* get("k1", 11) // returns "v1" | |
* get("k1", 21)... | |
*/ | |
import java.util.*; | |
class TimeTravelingHashTable { | |
. from: 1point3acres.com/bbs | |
// <key : <timestamp : value>> = <key: sorted values on timestamp> = <key : treemap> | |
HashMap<String, TreeMap<Integer, String>> map = new HashMap<>(); | |
// insert <timestamp, value> into hashmap | |
public void insert(String key, String value, int timestamp) { | |
if(map.containsKey(key)) { | |
Map<Integer, String> values = map.get(key); | |
values.put(timestamp, value); | |
} else { | |
TreeMap<Integer, String> values = new TreeMap<>(); | |
values.put(timestamp, value); | |
map.put(key, values); | |
} | |
} | |
// get the floor value on timestamp | |
public String get(String key, int timestamp) { | |
if(!map.containsKey(key)) return null; | |
return map.get(key).floorEntry(timestamp).getValue(); | |
} | |
// Return the latest value on timestamp | |
public String get(String key) { | |
return map.get(key).lastEntry().getValue(); | |
} | |
public static void main(String[] args) { | |
TimeTravelingHashTable hashtable = new TimeTravelingHashTable(); | |
hashtable.insert("k1", "v1", 10); | |
hashtable.insert("k1", "v2", 20); | |
hashtable.insert("k2", "v1", 5); | |
hashtable.insert("k2", "v2", 15); | |
System.out.println(hashtable.get("k1")); // "v1" | |
System.out.println(hashtable.get("k1", 11)); // "v1" | |
System.out.println(hashtable.get("k1", 15)); // "v1" | |
System.out.println(hashtable.get("k1", 11)); // "v1" | |
System.out.println(hashtable.get("k1", 21)); // "v2" | |
System.out.println(hashtable.get("k2", 10)); // "v1" | |
System.out.println(hashtable.get("k2", 20)); // "v2" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment