Leetcode 350. Intersection of Two Arrays II
题目链接: Intersection of Two Arrays II
难度:easy
题目大意:
输入两个数组,输出两个数组共有的元素,如果同一个元素多次重复,全部输出。
思路:
思路1:
用HashMap来统计数组nums1中的各个元素出现的次数,再遍历nums2,如果nums2中的元素在HashMap中存在,且出现次数大于零,则将这个元素存起来,并将HashMap中该元素的次数减一。最后将存起来的所有元素返回。
思路2:
先将nums1和nums2排序,分别遍历nums1和nums2,如果碰到两个数组中的元素相等,则将该元素存起来,最后返回存起来的元素。该方法比思路1更快。
代码
思路1(用HashMap实现):
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
TreeMap<Integer,Integer> map=new TreeMap<>();
for(int n:nums1){//统计nums1中各个数字出现的次数
map.put(n,map.getOrDefault(n,0)+1);
}
ArrayList<Integer> result=new ArrayList<Integer>();
for(int i=0;i<nums2.length;i++){
if(map.containsKey(nums2[i])&&map.get(nums2[i])>0){
result.add(nums2[i]);
map.put(nums2[i],map.get(nums2[i])-1);
}//map.get(nums2[i])减为0时,代表两个数组共有的某个数字已全部加入到result中
}
int []res=new int[result.size()];
for(int i=0;i<result.size();i++){
res[i]=result.get(i);
}
return res;
}
}
思路2(排序实现):
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
//高赞回答
if(nums1.length==0){
return nums1;
}
if(nums2.length==0){
return nums2;
}
Arrays.sort(nums1);
Arrays.sort(nums2);
int i=0,j=0,k=0;
while(i<nums1.length&&j<nums2.length){
if(nums1[i]<nums2[j]){
i++;
}
else if(nums2[j]<nums1[i]){
j++;
}
else{
nums1[k++]=nums1[i];
i++;
j++;
}
}
return Arrays.copyOfRange(nums1,0,k);
}
}