2014-02-17 50 views
2

想象一下,我们有两个列表,并且想知道另一个列表中元素的位置。为了说明:将列表中的元素映射到另一个列表中的位置

List<String> one = Arrays.asList("B", "I", "G"); 
List<String> another = Arrays.asList("L", "A", "R", "G", "E"); 

结果将是:

[-1, -1, 3] 

因为既不B或我发生在第二列表中,但G中对第三位置。

这是我想出了迄今:

<E> List<Integer> indices(List<E> elements, List<E> container) { 
    List<Integer> indices = new ArrayList<>(elements.size()); 
    for (int i = 0; i < elements.size(); i++) { 
     indices.add(container.indexOf(indices.get(i))); 
    } 
    return indices; 
} 

是否有避免List.indexOf()内部回路更快的解决方案吗?

+0

@Sneaky我很肯定的是一个动态编程方法可以从n * m个改进它与结合的可能接近n + m个,通过预处理每个阵列中序列和合并两个成公共数据结构可以检查重叠。 – chrylis

回答

4

您可以使用Map

Map<String, Integer> otherMap = new HashMap<>(other.size()); 
int index = 0; 
for(String otherElem : other) { 
    otherMap.put(otherElem, index++); 
} 

然后:

for(String oneElem : one) { 
    Integer index = otherMap.get(oneElem); 
    indices.add(index == null ? -1 : index); 
} 

这样做,你得到的指标,而不是直接每次寻找和索引的时间可能非常大名单上进行迭代。

+0

是的,刚刚来到相同的想法:-)你的代码比我的好,如果你不介意的话,我会使用你的代码。 – hoefling

+0

我绝对不介意。我希望它有助于:) –

2

您可以使用HashMap<String, Integer>将每个角色映射到其位置。然后用HashMap方法.containsKey()找出,如果某字符串存在于字段中并且.get()找出该位置。

HashMap<String, Integer> another; 

for (String str : one) { 

    if (another.contains(str)) { 
     result.add(another.get(str)); 
    } else { 
     result.add(-1); 
    } 
} 
相关问题