题目:
给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。
思路一: 统计较短数组放入HashMap集合
将两个数组中较短的数据统计每一个元素的个数到HashMap集合中,在另一个数组中找相同的元素放入交集数组中,直到遍历完成
思路二:双指针
两个数组分别对应两个指针,首先对两个数组分别排序,两指针分别指向排序后两数组的起始位置,如果对应数组元素相同,则将该元素放入交集数组,否则,将较小元素所在的数组指针+1,控制指针向下走,直到遍历完两数组中长度最小的数组为止。
java代码
package demo;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class leetcode5 {
//思路一
public int[] intersect(int[] nums1, int[] nums2) {
if(nums1.length>nums2.length){
return intersect(nums2,nums1);//递归使得nums1中始终放的是长度较小的数组
}
Map<Integer,Integer> hmap=new HashMap<Integer,Integer>();//定义hashmap集合
for(int num:nums1){
int count=hmap.getOrDefault(num,0)+1;//先统计nums1中各元素的次数
hmap.put(num,count);//存入hashmap集合
}
int[] intersection=new int[nums1.length];//交集数组最长不超过两数组最小长度
int n=0;//交集数组索引,方便最后遍历
for(int num:nums2){//从nums2中寻找与nums1相同的元素,放入交集集合中
int count=hmap.getOrDefault(num,0);
if(count>0){//正在遍历的当前元素是交集元素
intersection[n++]=num;//存入交集数组
count--;
if(count>0){//nums1中还有相同元素
hmap.put(num,count);//更新该元素个数
}
else{//没有了,只有一个
hmap.remove(num);//将该元素移除防止重复输出
}
}
}
return Arrays.copyOfRange(intersection,0,n);//返回数组
}
//思路二
public int[] intersect_doublepoint(int[] nums1, int[] nums2){
Arrays.sort(nums1);//先对两个数组排序
Arrays.sort(nums2);
int p1=0;//nums1指针
int p2=0;//nums2指针
int[] intersection=new int[Math.min(nums1.length,nums2.length)];//交集数组
int n=0;//交集数组索引
while(p1<nums1.length&&p2<nums2.length) {//使用&符号,代表只要有一个数组遍历完成就结束
if (nums1[p1] < nums2[p2]) {//将小的数组元素索引+1
p1++;
} else if (nums2[p2] < nums1[p1]) {//将小的数组元素索引+1
p2++;
}else{//出现交集元素
intersection[n++]=nums1[p1++];//两数组指针索引+1,交集数组索引+1
p2++;
}
}
return Arrays.copyOfRange(intersection,0,n);//最后返回数组
}
}
//测试
class test5{
public static void main(String arg[]){
leetcode5 l=new leetcode5();
int[] nums1={4,9,5};
int[] nums2={9,4,9,8,4};
//思路一
//int[] result=l.intersect(nums1,nums2);
//思路二
int[] result=l.intersect_doublepoint(nums1,nums2);
for(int i:result){
System.out.println(i);
}
}
}
复杂度分析
思路一
思路二