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

发布于 2024-11-17 03:45:15 字数 333 浏览 4 评论 0原文

我在这个程序中使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

眼眸里的快感 2024-11-24 03:45:15

NavigableMap 就可以了。

NavigableMap would do the trick.

再见回来 2024-11-24 03:45:15

集合库中的 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

TreeMap from the collections library provides the functionality you're looking for

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
远昼 2024-11-24 03:45:15

如果你想使用 sql 来做到这一点,类似:

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

会起作用。

If you wanted to do this using sql something like:

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

would work.

执笏见 2024-11-24 03:45:15

好吧,如果您主要从结构中读取数据并且很少插入数据,那么您可以使用简单的排序数组并进行二分搜索。如果您担心搜索性能,那就再简单不过了。现在,如果您定期更新结构,那就不太好了 - 那么您将不得不使用更复杂的东西。

我还认为 - 但不完全确定 - 二叉树不会同样有效吗?搜索正确节点应该所在的位置,如果未找到该值,则使用其前任节点。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文