【发布时间】:2017-03-11 05:19:55
【问题描述】:
假设我有 3 组字符串值:
水果:苹果、浆果、香蕉
颜色:红、蓝、橙
交通工具:汽车、飞机、卡车
我正在寻找使用 Java 检索每个集合的父值的最有效方法,例如:
getParentValue("banana") ---> 水果
解决方案 1:
创建一堆 if/else 语句或 switch case:
if (fruitSet.contains(elem)) {
return "fruit";
}
else if (colorSet.contains(elem)) {
return "color";
} ...
这会产生 O(n) 查找,n 是集合的数量。
解决方案 2:
创建一个将每个子项存储到父项值的哈希图,
Key/Value:
apple/fruit
berry/fruit
banana/fruit
red/color
blue/color
orange/color
...
这会产生 O(1) 的查找时间,但会在存储每个键时生成一个大的哈希映射 - 出于某种原因,这种解决方案感觉很难看。
我正在寻找一些可能更优雅的意见或其他方法。
【问题讨论】:
-
哈希图中的键数将等于所有集合中的元素数组合(来自解决方案 1)