每日一题:Leetcode-349 两个数组的交集

力扣题目

解题思路

java代码

力扣题目:

给定两个数组 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] 也是可通过的

解题思路:

算法原理
这道题通过使用哈希集合来找出两个整数数组的交集。

思路

  1. 首先,将两个数组分别转换为两个哈希集合 set1 和 set2 ,这样可以快速判断元素是否存在,并且去除重复元素。
  2. 然后,通过比较两个集合的大小,选择较小的集合进行遍历。
  3. 对于较小集合中的每个元素,检查它是否在另一个集合中存在,如果存在则将其添加到 intersectionSet 中。
  4. 最后,将 intersectionSet 转换为整数数组返回。

代码分析

  • 在 intersection 方法中,创建两个哈希集合并填充元素。
  • getIntersection 方法中,先处理集合大小的比较,然后遍历较小集合获取交集,并将交集集合转换为数组。

时间复杂度:O(M+N),其中 m 和 n 分别是两个数组的长度。创建集合和遍历的操作总体与数组长度之和成正比。

空间复杂度:O(M+N),主要用于存储两个哈希集合。

java代码:

package com.example.lib;

import java.util.HashSet;
import java.util.Set;

public class Leetcode349 {
    public static void main(String[] args) {
        Leetcode349 leetcode349 = new Leetcode349();
        int[] intersection = leetcode349.intersection(new int[]{1, 2, 2, 1}, new int[]{2, 2});
        for (int i : intersection){
            System.out.println(i);
        }
    }
    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) {
            set2.add(num);
        }
        return getIntersection(set1, set2);
    }

    public int[] getIntersection(Set<Integer> set1, Set<Integer> set2) {
        if (set1.size() > set2.size()) {
            return getIntersection(set2, set1);
        }
        Set<Integer> intersectionSet = new HashSet<Integer>();
        for (int num : set1) {
            if (set2.contains(num)) {
                intersectionSet.add(num);
            }
        }
        int[] intersection = new int[intersectionSet.size()];
        int index = 0;
        for (int num : intersectionSet) {
            intersection[index++] = num;
        }
        return intersection;
    }

}

更多详细内容同步到公众号,感谢大家的支持!

每天都会给刷算法的小伙伴推送明日一题,并且没有任何收费项

猜你喜欢

转载自blog.csdn.net/LIUCHANGSHUO/article/details/143033636