Data structure with two way O(1) lookup. Hashtable?

喜欢而已 提交于 2019-12-09 17:48:21

问题


I'm implementing a system where I have a list of names and each person has 1 phone number. I need to be able to take a name and look up the phone number, or take a phone number and look up a name.

I know I could do this by having two hashtables - one which goes from names to phone numbers and one which goes from phone numbers to names. Then I can look up in either direction in O(1) time. However this seems like I am storing too much data - every name and every phone number is stored twice.

Is there any way to do this more efficiently? What data structure should I use to store the names and phone numbers?

I am coding in Java if that is relevant.

Many thanks!


回答1:


Java does not provide a two-way hash table out-of-the-box. Your solution that relies on two hash tables is as good as it gets, unless you are willing to go with third-party libraries (which would hide the two hash tables for you) or re-implement a significant portion of HashMap<K,V>.

Then I can look up in either direction in O(1) time. However this seems like I am storing too much data - every name and every phone number is stored twice.

Not necessarily: you can use the same object that represents the phone number, in which case there would be a single object for the phone number, with two references to it stored from two hash tables.




回答2:


Consider using Guava's HashBiMap, which is basically two HashMaps linked together behind the scenes. See also the BiMap interface and its related article.




回答3:


  1. Remember that the object itself is stored only once, and not in both maps. You only need double number of references - so it might not be that bad.
  2. You can use Gauva BiMap that offers that functionality (and its interface HashBiMap)


来源:https://stackoverflow.com/questions/13314905/data-structure-with-two-way-o1-lookup-hashtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!