摘自:https://leetcode-cn.com/problems/intersection-of-two-arrays/solution/duo-chong-jie-fa-jie-jue-349-liang-ge-shu-zu-de-ji/
一.两个数组的交集
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
输出结果中的每个元素一定是唯一的。
我们可以不考虑输出结果的顺序。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/intersection-of-two-arrays
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
方法1:Set(题解中出现最多的)
即将两个数组转换成Set,因为Set具有无序性所以不用担心重复问题
集合Set:
- 确定性:对任意对象都能判定其是否属于某一个集合。
- 互异性:集合内每个元素都是无差异的,注意是内容差异。
- 无序性:集合内的顺序无关
Java中的集合接口Set
- HashSet(基于散列函数的集合,无序,不支持同步)
- TreeSet(基于树结构的集合,可排序的,不支持同步)
- LinkedHashSet(基于散列函数和双向链表的集合,可排序,不支持同步)
import java.util.*;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<Integer>();
Set<Integer> set2 = new HashSet<Integer>();
for(int num:nums1){
set1.add(num);
}
for(int num:nums2){
if(set1.contains(num)){
set2.add(num);
}
}
int g = 0;
int[] a = new int[set2.size()];
for(int num:set2){
a[g] = num;
g++;
}
return a;
}
}
方法2:双指针
先对两个数组进行排序,然后用双指针进行遍历
时间复杂度:O(nlogn)
import java.util.*;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int i