题目来源:https://leetcode-cn.com/problems/intersection-of-two-arrays-ii/
1.思路:先将两个数组排好序,用两个指针s1,s2分别同时遍历两个数组,如果两个指针指向的数相同,就一起后移并将结果存入list中。nums[s1]<nums[s2],那就s1后移;nums[s1]>nums[s2],就s2后移。最后遍历list,将结果集存放到数组中。
时间复杂度:O(m log m+n log n)
空间复杂度:O(min(m,n))
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int len1 = nums1.length,len2 = nums2.length;
ArrayList<Integer> res = new ArrayList();
int s1 = 0,s2 = 0;
while(s1<len1&&s2<len2){
if(nums1[s1]==nums2[s2]){
res.add(nums1[s1]);
s1++;
s2++;
}else if(nums1[s1]<nums2[s2]){
s1++;
}else{
s2++;
}
}
int[] ans = new int[res.size()];
for(int i = 0;i<res.size();i++){
ans[i] = res.get(i);
}
return ans;
}
}
2.看了官方题解,还可以用hash法
由于同一个数字在两个数组中都可能出现多次,因此需要用哈希表存储每个数字出现的次数。对于一个数字,其在交集中出现的次数等于该数字在两个数组中出现次数的最小值。
首先遍历第一个数组,并在哈希表中记录第一个数组中的每个数字以及对应出现的次数,然后遍历第二个数组,对于第二个数组中的每个数字,如果在哈希表中存在这个数字,则将该数字添加到答案,并减少哈希表中该数字出现的次数。
为了降低空间复杂度,首先遍历较短的数组并在哈希表中记录每个数字以及对应出现的次数,然后遍历较长的数组得到交集。
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if (nums1.length > nums2.length) {
return intersect(nums2, nums1);
}
HashMap<Integer,Integer> map = new HashMap();
ArrayList<Integer> res = new ArrayList();
//遍历短的那个数组,在map中记录出现过的数字及其出现的次数
for(int num:nums1){
if(map.containsKey(num)){
map.put(num,map.get(num)+1);
}else{
map.put(num,1);
}
}
//遍历长数组,若长数组中的数字在map中存在,加入结果集,key对应的次数也减少
for(int num:nums2){
int count = map.getOrDefault(num,0);
if (count > 0) {
res.add(num);
count--;
if (count > 0) {
map.put(num, count);
} else {
map.remove(num);
}
}
}
int[] ans = new int[res.size()];
for(int i = 0;i<res.size();i++){
ans[i] = res.get(i);
}
return ans;
}
}