如何比较两个数组并仅提取第二个数组中的独有值
实现思路
- 核心逻辑是筛选出
array_last中所有不存在于array_first的元素 - 小数据量下可以直接用遍历+包含判断实现
- 大数据量建议先将
array_first转为哈希集合(Set),降低查找的时间复杂度,整体复杂度从O(m*n)优化到O(m+n),其中m是array_last长度,n是array_first长度
不同语言实现示例
Python 实现
array_first = [1,2,3,4,5,8,9,10,11] array_last = [1,2,6,4,7,5,12] # 方法1:列表推导(小数据量适用) res = [x for x in array_last if x not in array_first] # 方法2:转Set优化查找效率(大数据量更优) first_set = set(array_first) res = [x for x in array_last if x not in first_set] print(res) # 输出 [6,7,12]
JavaScript 实现
const array_first = [1,2,3,4,5,8,9,10,11] const array_last = [1,2,6,4,7,5,12] // 方法1:直接filter判断 const res = array_last.filter(x => !array_first.includes(x)) // 方法2:Set优化性能 const firstSet = new Set(array_first) const res = array_last.filter(x => !firstSet.has(x)) console.log(res) // 输出 [6,7,12]
Java 实现
import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ArrayDiff { public static void main(String[] args) { Integer[] array_first = {1,2,3,4,5,8,9,10,11}; Integer[] array_last = {1,2,6,4,7,5,12}; Set<Integer> firstSet = new HashSet<>(); for (int num : array_first) { firstSet.add(num); } List<Integer> res = new ArrayList<>(); for (int num : array_last) { if (!firstSet.contains(num)) { res.add(num); } } System.out.println(res); // 输出 [6,7,12] } }
内容的提问来源于stack exchange,提问作者James Bond
相关产品推荐
相关产品推荐

