[英]Fast look up of key by value without creating an inverse hashmap?
If I have a HashMap<KEY, VALUE>
and I need fast look up of the key by the value is there any other approach besides creating a second HashMap<VALUE, KEY>
that store the same data but using the value as the key? 如果我有
HashMap<KEY, VALUE>
并且我需要通过值快速查找键,那么除了创建第二个HashMap<VALUE, KEY>
来存储相同的数据但使用值作为键之外,还有其他方法吗?
Is there any approach/tick about this? 是否有任何方法/勾选? If it makes a difference my interest is about
String
both as key and value 如果有所作为,我的兴趣是将
String
作为键和值
Note: I am on Java 7 注意:我使用的是Java 7
Update: 更新:
I am not sure why the other question is a duplicate as I am asking a specific way on implementing this. 我不确定为什么另一个问题是重复的,因为我在问实现此问题的具体方法。
Unless the only/best way is a 2 way map I can't see why this is a duplicate 除非唯一/最好的方法是双向地图,否则我看不出为什么这是重复的
Short answer: no, there isn't. 简短的回答:不,没有。
You need two maps. 您需要两张地图。 If you want to use O(1) time for both, that means two hashmaps.
如果您想同时使用O(1)时间,则意味着两个哈希图。
If you're worried about space, don't worry so much: you're just storing duplicate pointers, and not two strings. 如果您担心空间,则不必太担心:您只是存储重复的指针,而不是两个字符串。
Ie, you're just storing 即,您只是在存储
HashMap<String* k, String* v> normal;
HashMap<String* k, String* v> inverse;
rather than entire strings. 而不是整个字符串。 (Although pointers kind of don't exist in Java.)
(尽管Java中不存在指针。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.