我有两个整数数组/数组列表。我想知道从两个中找到重复项并存储到第三个中的最佳方法。
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}
谨致问候,Android IT
我更喜欢使用Set而不是HashMap,因为HashMap需要key-value
&Set谈论唯一性集合不允许重复
将两个数组的元素添加到HashMap中,其中的值是元素出现的次数。然后将其输出到一个数组。
你的意思是,集合并集?
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);
现在resultArray
包含
[1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 14, 15]
有效的方法是,对数组(O(n log n))进行排序,并遍历两个数组中最低的一个,只有在两个数组都在(O(n))时才选择它,否则丢弃。