题目描述
给定两个数组,编写一个函数来计算它们的交集。
示例:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
示例2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]
题目思路
双指针
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
ArrayList<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]){
list.add(nums1[i]);
i++;
j++;
}
else if(nums1[i]<nums2[j]){
i++;
}
else{
j++;
}
}
int [] arr = new int[list.size()];
int index = 0;
for (Integer integer : list) {
arr[index++] = integer.intValue();
}
return arr;
}
}
哈希表
首先遍历第一个数组,并在哈希表中记录第一个数组中的每个数字以及对应出现的次数,然后遍历第二个数组,对于第二个数组中的每个数字,如果在哈希表中存在这个数字,则将该数字添加到答案,并减少哈希表中该数字出现的次数。
public int[] intersect(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length) {
return intersect(nums2, nums1);
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int num : nums1) {
int count = map.getOrDefault(num, 0) + 1;
map.put(num, count);
}
int[] intersection = new int[nums1.length];
int index = 0;
for (int num : nums2) {
int count = map.getOrDefault(num, 0);
if (count > 0) {
intersection[index++] = num;
count--;
if (count > 0) {
map.put(num, count);
} else {
map.remove(num);
}
}
}
return Arrays.copyOfRange(intersection, 0, index);
}