给定一个有序地图<string,list<sting>>
:
k1 [v1,v2,v5]
k2 [v1]
k3 [v4,v5]
k4 [v2]
还有一组字符串[buckets]:
v2 v4 v5
输出是一张地图:
v2 [k1,k4]
v4 [k3]
v5 [k1, k3]
订单在产出中很重要。 难道有一种更好的方式然后简单的蛮力,编程语言是java ??
答案 0 :(得分:0)
只需迭代地图并将值收集到SortedMap
持有SortedSet
s(例如,TreeMap
TreeSet
s),留下排序和重复过程到底层数据结构:
Map<String, List<String> input = ...;
Set<String> buckets = ...;
SortedMap<String, TreeSet> output = new TreeMap<String, TreeSet>();
for (Map.Entry<String, List<String> entry : input) {
List<String> possibleBuckets = entry.getValue();
for (String possibleBucket : possibleBuckets) {
if (buckets.contains(possibleBucket) {
Set<String> set = output.get(possibleBucket);
if (set == null) {
set = new TreeSet<String>();
output.put (possibleBucket, set);
}
set.add (entry.getKey());
}
}
}