public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
// Write your code here
Map<Integer,Integer> map = new HashMap<>();
int length1 = nums1.length;
for (int i = 0; i < length1; i++) {
if (map.containsKey(nums1[i])) {
map.put(nums1[i], map.get(nums1[i]) + 1);
} else {
map.put(nums1[i], 1);
}
}
ArrayList<Integer> list = new ArrayList<>();
int length2 = nums2.length;
for (int i = 0; i < length2; i++) {
if (map.containsKey(nums2[i])) {
list.add(nums2[i]);
if (map.get(nums2[i]) == 1) map.remove(nums2[i]);
else map.put(nums2[i], map.get(nums2[i]) - 1);
}
}
int length = list.size();
int[] result = new int[length];
for (int i = 0; i < length; i++) {
result[i] = list.get(i);
}
return result;
}
}
548.Intersection of Two Arrays II
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- Intersection of Two Arrays IIGiven two arrays, write a fu...
- 原题是: Given two arrays, write a function to compute their ...
- Given two arrays, write a function to compute their inter...