问题描述:
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
求两个数组的交集,不考虑顺序,不删减重复
限制条件:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
思路:
先排序。每个集合设立一个头指针pt1,pt2,比较其指向的值,若pt1小于pt2,则pt1++;若相等,则加入该元素,且都++; 若pt1大于pt2,pt2++;
关键一点:如果遇到想使用array但是不确定其大小的情况,可以使用arraylist,最终转换为array。转换的方式有很多种,我这里用的是逐一get。因为使用toArray会出现数据类型不匹配的错误。
代码如下:
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> myList = new ArrayList<>();
int pt1 = 0;
int pt2 = 0;
while ((pt1<nums1.length) && (pt2<nums2.length)){
if(nums1[pt1]<nums2[pt2]){
pt1++;
}
else if (nums1[pt1]==nums2[pt2]){
myList.add(nums1[pt1]);
pt1++;
pt2++;
}
else{
pt2++;
}
}
int[] ans = new int[myList.size()];
for (int i=0; i<myList.size(); i++){
ans[i]=myList.get(i);
}
return ans;
}
}
时间复杂度: O(nlogn), 受制于排序算法的速度。
方法二:用哈希表
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
//we assume nums1 is smaller than nums2 in length, otherwise we swap them first
if(nums1.length>nums2.length){
return intersect(nums2, nums1);
}
List<Integer> list=new ArrayList<>();
Map<Integer, Integer> map=new HashMap<>();
for(int i=0; i<nums1.length; i++){
if(!map.containsKey(nums1[i])){
map.put(nums1[i], 1);
}
else{
map.replace(nums1[i], map.get(nums1[i])+1);
}
}
for(int i=0; i<nums2.length; i++){
if((map.containsKey(nums2[i]))&&(map.get(nums2[i])>0)){
list.add(nums2[i]);
map.replace(nums2[i], map.get(nums2[i])-1);
}
}
int[] ans=new int[list.size()];
for(int i=0; i<list.size(); i++){
ans[i]=list.get(i);
}
return ans;
}
}
时间复杂度: O(m+n)
空间复杂度: O(min(m,n))