今日签到题,题目如下
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
示例 2:输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
说明:输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
我们可以不考虑输出结果的顺序。
进阶:如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小很多,哪种方法更优?
如果 nums2 的元素存储在磁盘上,磁盘内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
暴力解法
遇题不决,先暴力解。暴力解法思路过于简单就不写了。
复杂度分析:
两层嵌套循环,时间复杂度为O(M*N)。只使用了一个 List 保存答案,空间复杂度为 O(1)。
以下为自己提交的代码:
public class Solution {
public int[] Intersect(int[] nums1, int[] nums2) {
List<int> ansList = new List<int>();
bool[] boolArr = new bool[nums2.Length];
for (int i = 0; i < nums1.Length; i++)
{
for (int j = 0; j < nums2.Length; j++)
{
if (!boolArr[j] && nums2[j] == nums1[i])
{
ansList.Add(nums1[i]);
boolArr[j] = true;
break;
}
}
}
return ansList.ToArray();
}
}
好了,自己思考部分就这样,接下来就是看官方题解优化了。
官方题解有两种方法
- 哈希表
- 排序后双指针
哈希表对应进阶问题2,排序后双指针对应进阶问题1,进阶问题3通过归并排序后双指针解决。以下回顾哈希表和排序后双指针。
哈希表
因为我用的是 C#,所以使用字典。用一个 List 记录答案,用一个字典存储较小数组,key 值为数组值,value 为值出现的次数。然后遍历另一个数组查询字典,如果存在则为交集,在 List 当中添加,如果对应 value > 1 则减 ,不然就 Remove。遍历结束后返回结果 List.ToArray()。
复杂度分析:
分别遍历两个数组各一次,一次用作存入字典,一次用作比较字典,时间复杂度为 O(M + N)。不知道为什么提交的结果跟暴力解法耗时差不多,有大佬路过的话望指教。
使用一个字典存储较小数组,空间复杂度为O(min(M,N))。自己的代码中是直接存储 nums1 的,不想改了。
以下为自己提交的代码:
public class Solution {
public int[] Intersect(int[] nums1, int[] nums2) {
Dictionary<int,int> numsDict = new Dictionary<int,int>();
for (int i = 0; i < nums1.Length;i++)
{
if (numsDict.ContainsKey(nums1[i]))
{
numsDict[nums1[i]]++;
}
else
{
numsDict.Add(nums1[i],1);
}
}
List<int> numsList = new List<int>();
for (int j = 0;j < nums2.Length;j++)
{
if (numsDict.ContainsKey(nums2[j]))
{
numsList.Add(nums2[j]);
if (numsDict[nums2[j]] > 1)
{
numsDict[nums2[j]]--;
}
else
{
numsDict.Remove(nums2[j]);
}
}
}
return numsList.ToArray();
}
}
排序后双指针
如果两个数组已排序,则在查询 nums1[i] 是否存在 nums2 中的时候,此时如果已知 nums2[j] < nums1[i],则不需要查询 nums2[j] 之前的元素,因为他们都小于 nums1[i]。
使用两个整型变量 index1 和 index2 分别标记当前查询 nums1 和 nums2 的元素对应的下标。比较 nums1[index1] 和 nums2[index2],如果相等就加入记录结果的列表,然后将 index1 和 index2 加一,否则将较小的下标加一。反复比较直到其中一个下标到达数组边界。
数组排序的时间复杂度我还不是很明确,复杂度分析直接引用官方题解:
提交后时间消耗和以上两个解法时间差不多,但是较为稳定,还没理解为什么,同样也希望有路过的大佬能指点。
以下为自己提交的代码:
public class Solution {
public int[] Intersect(int[] nums1, int[] nums2) {
Array.Sort(nums1);
Array.Sort(nums2);
int index1 = 0;
int index2 = 0;
List<int> numsList = new List<int>();
while (index1 < nums1.Length && index2 < nums2.Length)
{
if (nums1[index1] == nums2[index2])
{
numsList.Add(nums1[index1]);
index1++;
index2++;
}
else if (nums1[index1] > nums2[index2])
{
index2++;
}
else
{
index1++;
}
}
return numsList.ToArray();
}
}