题目
给定两个数组,编写一个函数来计算它们的交集。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
说明:
- 输出结果中的每个元素一定是唯一的。
- 我们可以不考虑输出结果的顺序。
解法
解法一: 遍历数组,把目标数组放进Set中,再做判断。
class Solution {
/**
方法一:遍历数组,把目标数组放进Set中,再做判断。
*/
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1 == null || nums2 == null){
return null;
}
Set<Integer> set = new HashSet<>();
for(int n : nums2){
set.add(n);
}
Set<Integer> res = new HashSet<>();
for(int n : nums1){
if(set.contains(n)){
res.add(n);
}
}
int[] ans = new int[res.size()];
int index = 0;
for(int n : res){
ans[index++] = n;
}
return ans;
}
}
解法二: 双指针法。
class Solution {
/**
方法二:双指针。
*/
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1 == null || nums2 == null){
return null;
}
// 对两个数组排序
Arrays.sort(nums1);
Arrays.sort(nums2);
int i = 0 , j = 0;
Set<Integer> set = new HashSet<>();
while(i < nums1.length && j < nums2.length){
if(nums1[i] == nums2[j]){
set.add(nums1[i]);
i++;
j++;
} else if (nums1[i] < nums2[j]){
i++;
} else {
j++;
}
}
int[] res = new int[set.size()];
int index = 0 ;
for(int n : set){
res[index++] = n;
}
return res;
}
}
总结
本篇文章讲解了算法题目的思路和解法,代码和笔记由于纯手打,难免会有纰漏,如果发现错误的地方,请第一时间告诉我,这将是我进步的一个很重要的环节。以后会定期更新算法题目以及各种开发知识点,如果您觉得写得不错,不妨点个关注,谢谢。