[英]Find indices of common elements in arraylists in java
我有幾個沒有重復元素的ArrayLists。 我想在每個arraylist中找到它們的交集並返回常用元素的索引。
例如,如果我輸入為{0,1,2},{3,0,4},{5,6,0}
,那么我想返回{0},{1},{2}
即索引這里的共同元素0。
我能想到的一種方法是在所有ArrayLists上使用連續的retainAll()
來獲取交集,然后使用indexOf()
為每個輸入ArrayList查找交集元素的索引。
有沒有更好的方法呢?
首先對列表進行排序至少需要O(nlogn)
時間。 如果您正在尋找更高效的算法,您可以使用哈希映射獲得O(n)
。
例如用
A=[0,1,2],B=[3,0,4],C=[5,6,0]
您可以循環遍歷每個列表,並在元素上添加帶有哈希的元素。 最終的哈希看起來像
H = {0:[0,1,2], 1:[1], 2:[2], 3:[0], 4:[2], 5:[0], 6:[1]}
這里,鍵是元素,值是其對應列表中的索引。 現在,只需循環遍歷hashmap,找到大小為3的任何列表,在這種情況下,獲取索引。
代碼看起來像這樣(未經測試):
int[][] lists = {{0,1,2}, {3,0,4}, {5,6,0}};
// Create the hashmap
Map<Integer, List<Integer>> H = new HashMap<Integer, List<Integer>>();
for(int i = 0; i < lists.length; i++){
for(int j = 0; j < lists[0].length; j++){
// create the list if this is the first occurance
if(!H.containsKey(lists[i][j]))
H.put(lists[i][j], new ArrayList<Integer>());
// add the index to the list
H.get(lists[i][j]).add(j);
}
}
// Print out indexes for elements that are shared between all lists
for(Map.Entry<Integer, List<Integer>> e : H.entrySet()){
// check that the list of indexes matches the # of lists
if(e.getValue().size() == lists.length){
System.out.println(e.getKey() + ":" + e.getValue());
}
}
編輯:剛剛注意到你建議在你的問題中使用retainAll()。 那也是O(n)。
這是一個非常低效但相當可讀的解決方案,使用流返回列表列表。
int source[][];
Arrays.stream(source)
.map(list -> IntMap.range(0, list.length)
.filter(i -> Arrays.stream(source)
.allMatch(l -> Arrays.binarySearch(l, list[i]) >= 0))
.collect(Collectors.toList()))
.collect(Collectors.toList());
如果需要,您可以添加toArray調用以轉換為數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.