简体   繁体   中英

Java - Optimized way to find duplicates from two ArrayLists/Array

I have two Arrays/ArrayLists of Integer. I want to know the optmized way to find duplicates from two and store into the third one.

Array1 = {1,2,3,6,9,10,15,4};  
Array2 = {4,8,6,5,12,14,1,2,9};  
Result Array= {1,2,3,6,9,10,15,4,8,5,12,14,9}

Regards, Android IT

I would prefer to use Set over HashMap as HashMap need key-value & Sets talks about UNIQUENESS . Sets don't allow duplicates...

Add elements of both arrays into a HashMap where the value is the number of times the element occurs. Then output it to an array.

You mean, a set union?

List<Integer> array1 = Arrays.asList(1,2,3,6,9,10,15,4);
Set<Integer> set1 = new HashSet<Integer>(array1);

List<Integer> array2 = Arrays.asList(4,8,6,5,12,14,1,2,9);
Set<Integer> set2 = new HashSet<Integer>(array2);

set1.addAll(set2);
List<Integer> resultArray = new ArrayList<Integer>(set1);

Now resultArray contains

[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15]

一种有效的方法是对数组(O(n log n))进行排序,并遍历两个数组中的最低数组,仅在两个数组中都为(O(n))时才选择它,否则将其丢弃。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM