简体   繁体   English

这个问题的最佳数据结构?

[英]Best data structure for this problem?

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 我正在为这个程序使用Java,我目前有一种情况,我希望将键/值对添加到具有整数键的表中,例如

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" 所以例如,如果我查找7,它应该返回“Sue”,但是如果我查找9,它应该返回“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. 我希望使用其中一个java util类(HashTable,TreeMap等),但我不太清楚如何做到这一点。

NavigableMap可以解决问题。

TreeMap from the collections library provides the functionality you're looking for 集合库中的TreeMap提供了您正在寻找的功能

TreeMap<Integer,String> tree = new TreeMap<Integer,String>();
tree.put (1, "Bobby");
tree.put(6, "Sue");
tree.put (3, "Mary");
tree.put (8, "John");
tree.put (15, "Joe");
System.out.println(tree.floorEntry(7)); // Sue
System.out.println(tree.floorEntry(9)); // John

If you wanted to do this using sql something like: 如果你想使用sql这样做:

select top 1 * from hashTable where keyColumnId >= @passedValueId

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. 搜索正确节点应该在的位置,如果找不到该值,则使用其前一个节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM