package day05;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
//两个数组的交集,考虑元素出现的次数
// nums1 = [1,2,2,1], nums2 = [2,2] 输出:[2,2]
//nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出:[4,9]
public class InterSect {
public static void main(String[] args) {
int[] nums1 = {2,2,1};
int[] nums2 = {1,2,2,1};
//测试思路1
//int [] ans = intersect(nums1, nums2);
//测试思路2
int [] ans = intersect02(nums1, nums2);
System.out.println(Arrays.toString(ans));
}
//思路1:找两个数组的交集,即找两个数组的重复数字,使用一个Map存储较小的数组及其每个元素出现的次数
public static int [] intersect(int[] nums1, int[] nums2) {
if(nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
HashMap<Integer,Integer> hm = new HashMap<>();
int [] ans;
if(nums1.length > nums2.length) {
insertMap(hm,nums2);
ans = getIntersection(hm,nums1);
} else {
insertMap(hm,nums1);
ans = getIntersection(hm,nums2);
}
return ans;
}
public static void insertMap(HashMap<Integer,Integer> hm, int [] nums) {
for(int i = 0; i < nums.length; i++) {
if(hm.isEmpty()) {
hm.put(nums[i],1);
} else if (hm.containsKey(nums[i])) {
hm.put(nums[i],hm.get(nums[i]) + 1);//Map.get()返回的是key对应的值value,出现次数+1
} else {
hm.put(nums[i],1);
}
}
}
public static int[] getIntersection(HashMap<Integer,Integer> hm, int [] nums) {
ArrayList<Integer> res = new ArrayList<>();
for(int i = 0; i < nums.length; i++) {
if(hm.containsKey(nums[i]) && hm.get(nums[i]) != 0) {
res.add(nums[i]);
hm.put(nums[i],hm.get(nums[i]) - 1);//出现次数-1
}
}
int[] ans = new int[res.size()];
for(int i = 0; i < res.size(); i ++) {
ans[i] = res.get(i);
}
return ans;
}
//思路2:我们也可以使用两个集合Set,遍历较小的集合查看其中的元素是否在较大的集合中,此思路解决 重复的数字 交集只要 一个
public static int[] intersect02(int[] nums1, int[] nums2) {
if(nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
HashSet<Integer> hs1 = new HashSet<>();
for(Integer n : nums1) {
hs1.add(n);
}
HashSet<Integer> hs2 = new HashSet<>();
for(Integer n : nums2) {
hs2.add(n);
}
if(hs1.size() < hs2.size()) {
return getIntersection02(hs1,hs2);
} else {
return getIntersection02(hs2,hs1);
}
}
public static int[] getIntersection02(HashSet<Integer> hs1, HashSet<Integer> hs2) {
int[] res = new int[hs1.size()];
int index = 0;
for(Integer n : hs1) {
if(hs2.contains(n)) {
res[index] = n;
index += 1;
}
}
return Arrays.copyOf(res,index);
}
//思路3,使用内置函数retainAll-->将两个集合的交集返回给调用者
public static int[] intersect03(int[] nums1, int[] nums2) {
if(nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return new int[0];
}
HashSet<Integer> hs1 = new HashSet<>();
for(Integer n : nums1) {
hs1.add(n);
}
HashSet<Integer> hs2 = new HashSet<>();
for(Integer n : nums2) {
hs2.add(n);
}
//retainAll
hs1.retainAll(hs2);
int [] res = new int[hs1.size()];
int index = 0;
for(int n : hs1) {
res[index] = n;
index ++;
}
return res;
}
}
两个数组的交集的三种解决思路及其JAVA代码实现
最新推荐文章于 2022-12-27 02:21:23 发布