【力扣算法 LeetCode】349. intersection of two arrays 两个数组的交集


前言

题目出自力扣
算法练习题:两个数组的交集


一、题目

题目
给定两个数组 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 能节约内存


总结

继续加油

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值