题目:
给定两个数组,编写一个函数来计算它们的交集。
不能像349题那样使用HashSet,HashSet不包括重复的数。
思路
首先遍历第一个数组,并在哈希表中记录第一个数组中的每个数字以及对应出现的次数
然后遍历第二个数组,对于第二个数组中的每个数字,如果在哈希表中存在这个数字,则将该数字添加到答案,并减少哈希表中该数字出现的次数。
为了降低空间复杂度,首先遍历较短的数组并在哈希表中记录每个数字以及对应出现的次数,然后遍历较长的数组得到交集。
代码
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if(nums1.length > nums2.length){
return intersect(nums2,nums1);
}
Map<Integer,Integer> map = new HashMap<>();
for(int i : nums1){
int count = map.getOrDefault(i,0) +1;
map.put(i,count);
}
int[] ans = new int[nums1.length];
int index = 0;
for(int i : nums2){
int count = map.getOrDefault(i,0);
if(count > 0){
ans[index++] = i;
count--;
if(count > 0){
map.put(i,count);
}else{
map.remove(i);
}
}
}
return Arrays.copyOfRange(ans,0,index);
}
}
方法:排序+双指针
如果两个数组是有序的,则可以使用双指针的方法得到两个数组的交集。
首先对两个数组进行排序,然后使用两个指针遍历两个数组。
初始时,两个指针分别指向两个数组的头部。每次比较两个指针指向的两个数组中的数字,如果两个数字不相等,则将指向较小数字的指针右移一位,如果两个数字相等,将该数字添加到答案,并将两个指针都右移一位。当至少有一个指针超出数组范围时,遍历结束。
**return Arrays.copyOfRange(intersection, 0, index);** 主要用于对一个已有的数组进行截取复制,复制出一个**左闭右开**区间的数组。
Arrays.copyOfRange(T[ ] original,int from,int to)
将一个原始的数组original,从下标from开始复制,复制到上标to,生成一个新的数组。
注意这里包括下标from,不包括上标to。
代码
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int length1 = nums1.length;
int length2 = nums2.length;
int[] intersection = new int[Math.min(length1,length2)];
int index1 = 0, index2 = 0,index = 0;
while(index1 < length1 && index2 < length2 ){
if(nums1[index1] > nums2[index2]){
index2++;
}else if(nums1[index1] < nums2[index2]){
index1++;
}else{
intersection[index++] = nums1[index1];
index1++;
index2++;
}
}
return Arrays.copyOfRange(intersection, 0, index);
}
}