这个问题的最佳数据结构?
我在这个程序中使用Java,目前我想将键/值对添加到带有整数键的表中,就像所以
add (1, "Bobby")
add (6, "Sue")
add (3, "Mary")
add (8, "John")
add (15, "Joe")
很自然地我想做一些类似哈希表的事情,但是当我进行查找时,如果它找不到确切的值,我希望它返回不大于请求的键的最近的键。
例如,如果我查找 7,它应该返回“Sue”,但如果我查找 9,它应该返回“John”
我希望使用 java util 类之一(HashTable、TreeMap 等),但我'我不太确定该怎么做。
I am using Java for this program, and I currently have a situation where I want to add key/value pairs to a table with integer keys, like
add (1, "Bobby")
add (6, "Sue")
add (3, "Mary")
add (8, "John")
add (15, "Joe")
So naturally I want to do something like a hashtable, but when I do a lookup, if it doesn't find the exact value, I would like it to return the nearest key that isn't greater than the requested key.
So for example, if I lookup 7, it should return "Sue", but if I lookup 9, it should return "John"
I'm hoping to use one of the java util classes (HashTable, TreeMap, etc) but I'm not quite sure how to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
NavigableMap 就可以了。
NavigableMap would do the trick.
集合库中的 TreeMap 提供了您正在寻找的功能
TreeMap from the collections library provides the functionality you're looking for
如果你想使用 sql 来做到这一点,类似:
会起作用。
If you wanted to do this using sql something like:
would work.
好吧,如果您主要从结构中读取数据并且很少插入数据,那么您可以使用简单的排序数组并进行二分搜索。如果您担心搜索性能,那就再简单不过了。现在,如果您定期更新结构,那就不太好了 - 那么您将不得不使用更复杂的东西。
我还认为 - 但不完全确定 - 二叉树不会同样有效吗?搜索正确节点应该所在的位置,如果未找到该值,则使用其前任节点。
Well if you mostly read data from the structure and insert rarely you could use a trivial sorted array and do a binary search. Can't get much simpler or simpler if you're worried about search performance. Now not that great if you regularly update the structure - then you'll have to use something more complicated.
Also I think - but not totally sure - wouldn't a binary tree work just as well? Search for the position where the correct node should be and use its predecessor if the value isn't found.