给定两个数组,编写一个函数来计算它们的交集。
Given two arrays, write a function to compute their intersection.
示例 1:
输入: nums1 = [1,2,2,1], nums2 = [2,2]
输出: [2,2]
示例 2:
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出: [4,9]
说明:
Note:
进阶:
Follow up:
暴力解题就不说了。
i, j
,移动指针输入 nums1 = [ 4, 9, 5 ], nums2 = [ 9, 4, 9, 8, 4 ]
排序 nums1 = [ 4, 5, 9 ], nums2 = [ 4, 4, 8, 9, 9 ]
双指针遍历:[ 4, 5, 9],[ 4, 4, 8, 9, 9 ]
^ ^
4 = 4, 存入 res = [4], 移动双指针: [ 4, 5, 9],[ 4, 4, 8, 9, 9 ]
^ ^
5 > 4, 移动指向 4 的指针:[ 4, 5, 9],[ 4, 4, 8, 9, 9 ]
^ ^
5 < 8, 移动指向 5 的指针:[ 4, 5, 9],[ 4, 4, 8, 9, 9 ]
^ ^
9 > 8, 移动指向 8 的指针:[ 4, 5, 9],[ 4, 4, 8, 9, 9 ]
^ ^
9 = 9, 存入 res = [4, 9], 移动双指针: [ 4, 5, 9 ],[ 4, 4, 8, 9, 9 ]
^ ^
超过 nums1 长度,结束,返回 res
回答进阶问题:
Java:
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
HashMap<Integer, Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();//动态数组
for (Integer num : nums1) map.put(num, map.getOrDefault(num, 0) + 1);//统计元素出现频次
for (Integer num : nums2) {//遍历另一个数组
if (map.containsKey(num)) {
int tmp = map.get(num)-1;//频次减一
if (tmp == 0) map.remove(num);//频次为 0 时,移出 HashMap
else map.put(num, tmp);//否则更新频次
list.add(num);//加入动态数组
}
}
//转为数组并返回
int size=list.size();
int[] res = new int[size];
for (int i = 0; i < size; i++) res[i] = list.get(i);
return res;
}
}
Python:
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
count = dict(collections.Counter(nums1))# 自带库统计元素出现频次,并转为 Dict 类型
res = []
for num in nums2:# 遍历另一个数组
if num in count:
count[num] -= 1# 词频减一
res.append(num)
if count[num] <= 0:# 词频为 0 时,移出字典
count.pop(num)
return res
Java:
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> list = new ArrayList<>();
Arrays.sort(nums1);//排序数组
Arrays.sort(nums2);
int i = 0, j = 0;//定义指针
while (i < nums1.length && j < nums2.length) {
if (nums1[i] < nums2[j]) i++;//移动较小数的指针
else if (nums1[i] > nums2[j]) j++;//移动较小数的指针
else {
//两数相等则为交集,存入动态数组,移动双指针
list.add(nums1[i]);
i++;
j++;
}
}
//转为数组并返回
int[] res = new int[list.size()];
for (int k = 0; k < list.size(); k++) res[k] = list.get(k);
return res;
}
}
Python:
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
i, j, nums1_size, nums2_size = 0, 0, len(nums1), len(nums2)# 定义指针,计算数组长度
nums1, nums2, res = sorted(nums1), sorted(nums2), []# 排序数组,初始化返回数组 res
while i < nums1_size and j < nums2_size:# 循环条件为指针不溢出
if nums1[i] < nums2[j]:# 移动数值较小的指针
i += 1
elif nums1[i] > nums2[j]:# 移动数值较小的指针
j += 1
else:
res.append(nums1[i])# 数值相等,则为交集,移动双指针
i += 1
j += 1
return res