题目:
给定两个数组,编写一个函数来计算它们的交集。
示例:
代码:
- 解法一
//利用映射实现
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
TreeMap<Integer,Integer> map=new TreeMap<Integer,Integer>();
for(int nums:nums1){ //nums1的键,值放入map中
if(!map.containsKey(nums)){ //不存在时,值为1
map.put(nums,1);
}else{ //存在时 值为当前值+1
map.put(nums,map.get(nums)+1);
}
}
ArrayList<Integer> list=new ArrayList<Integer>();
for(int nums:nums2){
if(map.containsKey(nums)){ //map中有交集元素时
list