排序数组之间的最长公共子序列
难度:
标签:
题目描述
代码结果
运行时间: 44 ms, 内存: 16.6 MB
/*
* LeetCode Problem 1940: Longest Common Subsequence Between Sorted Arrays
* Problem Description:
* Given a 2D integer array arrays where each arrays[i] is a sorted array of distinct integers,
* return the longest common subsequence between all the arrays.
* A subsequence is a sequence that can be derived from another sequence by deleting some elements
* (possibly none) without changing the order of the remaining elements.
*
* Solution Approach using Java Streams:
* 1. Use a Map to store the count of each element across all arrays.
* 2. Use streams to iterate through each array and count the frequency of each element.
* 3. Filter elements that appear in all arrays and collect them as the result.
*/
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Solution {
public List<Integer> longestCommonSubsequence(int[][] arrays) {
Map<Integer, Long> frequencyMap = Stream.of(arrays)
.flatMapToInt(Arrays::stream)
.boxed()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
int numArrays = arrays.length;
return frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == numArrays)
.map(Map.Entry::getKey)
.sorted()
.collect(Collectors.toList());
}
}
解释
方法:
这个解法的思路是通过集合运算来找出所有给定数组中的公共元素。首先,它初始化一个集合 `cc` ,包含第一个数组的所有元素。随后,它遍历剩余的数组,并通过取交集操作更新 `cc` 集合,确保 `cc` 中只保留那些在所有数组中都出现的元素。最后,将得到的公共元素集合转换为列表,并对其进行排序,然后返回这个排序后的列表。
时间复杂度:
O(kn)
空间复杂度:
O(n)
代码细节讲解
🦆
在处理多个数组的公共元素时,为什么选择使用集合而不是其他数据结构,如列表或字典?
▷🦆
初始化集合`cc`为第一个数组的所有元素,这种做法会不会在某些情况下限制算法的效率?
▷🦆
在使用`cc.intersection(set(t))`更新集合时,是否考虑了所有数组元素数量极不均匀的情况,这会如何影响性能?
▷