Title: Intersection of Two Arrays II 350
Difficulty:Easy
原题leetcode地址: https://leetcode.com/problems/intersection-of-two-arrays-ii/
1. 见代码注释
时间复杂度:O(n),三次一层for循环。
空间复杂度:O(n),申请map和链表list以及需要返回的数组。
/**
* nums1数据存放map中
* nums1和nums2中相同且重复的数据存放list中
* 将list中数据转换成返回的数组
* @param nums1
* @param nums2
* @return
*/
public static int[] intersect(int[] nums1, int[] nums2) {
if (nums1.length == 0 || nums2.length == 0) {
return new int[]{};
}
Map<Integer, Integer> map = new HashMap<>();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums1.length; i++) {
map.put(nums1[i], map.getOrDefault(nums1[i], 0) + 1);
}
for (int i = 0; i < nums2.length; i++) {
if (map.containsKey(nums2[i]) && map.get(nums2[i]) > 0) {
list.add(nums2[i]);
map.put(nums2[i], map.get(nums2[i]) - 1);
}
}
int res[] = new int[list.size()];
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
return res;
}