前言
题目出自力扣
算法练习题:两个数组的交集
一、题目
题目
给定两个数组 nums1 和 nums2 ,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
测试用例
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
解释:[4,9] 也是可通过的
来源:力扣(LeetCode)
二、解答
1.代码
代码如下(示例):
//方法1
import java.util.HashSet;
import java.util.Set;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//先比较长度 选取比较短的就可减少比较次数
if (nums1.length< nums2.length){
return getInterSection(nums1, nums2);
}else {
return getInterSection(nums2,nums1);
}
}
public static int[] getInterSection(int[] nums1, int[] nums2) {
//用HashSet
Set<Integer> n1 = new HashSet<>();
Set<Integer> setInterSection = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
n1.add(nums1[i]);
}
for (int i = 0; i < nums2.length; i++) {
//判断是否有相同的数字
if (n1.contains(nums2[i])) {
setInterSection.add(nums2[i]);
}
}
int[] result = new int[setInterSection.size()];
int index = 0;
for (Integer value : setInterSection) {
result[index] = value;
index ++;
}
return result;
}
}
//leetcode submit region end(Prohibit modification and deletion)
/*
解答成功:
执行耗时:2 ms,击败了95.05% 的Java用户
内存消耗:41.3 MB,击败了56.10% 的Java用户
*/
// 方法2 改变了
import java.util.HashSet;
import java.util.Set;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//先比较长度 选取比较短的就可减少比较次数
if (nums1.length< nums2.length){
// 对于这里做出了改变
return getInterSection(nums2, nums1);
}else {
return getInterSection(nums1,nums2);
}
}
public static int[] getInterSection(int[] nums1, int[] nums2) {
//。。。。。。。。
}
//leetcode submit region end(Prohibit modification and deletion)
/*解答成功:
执行耗时:2 ms,击败了95.05% 的Java用户
内存消耗:41.4 MB,击败了44.85% 的Java用户
内存消耗大了
*/
2.复盘
这道题我觉得还算满意。
在 public static int[] getInterSection(int[] nums1, int[] nums2) 里面
使用 public static 能节约内存
总结
继续加油