LeetCode12|两个数组的交集

时间:2022-07-23
本文章向大家介绍LeetCode12|两个数组的交集,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1,问题简述

给定两个数组,编写一个函数来计算它们的交集。

2,示例

输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

3,题解思路

使用HashSet集合过滤元素,加上集合求交集的操作进行操作

4,题解程序

 
import java.util.HashSet;

public class IntersectionTest {
    public static void main(String[] args) {
        int[] nums1 = {1, 2, 2, 1};
        int[] nums2 = {2, 2};
        int[] intersection = intersection(nums1, nums2);
        for (int j : intersection) {
            System.out.print(j + "t");
        }
    }

    public static int[] intersection(int[] num1, int[] num2) {
        if (num1 == null || num1.length == 0 || num2 == null || num2.length == 0) {
            return new int[0];
        }
        HashSet<Integer> num1Set = new HashSet<>(num1.length);
        HashSet<Integer> num2Set = new HashSet<>(num2.length);
        for (Integer num : num1
        ) {
            num1Set.add(num);
        }
        for (Integer num : num2
        ) {
            num2Set.add(num);
        }
        num1Set.retainAll(num2Set);
        int[] result = new int[num1Set.size()];
        int i = 0;
        for (Integer integer : num1Set) {
            result[i++] = integer;
        }
        return result;
    }
}

5,总结

这道题没有什么难度,就是一次集合的简单操作,不过每个人的解题思路都不一样,看自己的操作吧,今天写了这部分文章之后也觉得文章的风格没怎么变化,简单,给与示例程序,顺便自己总结一下做过的内容,没有什么文字可写的了,但是文章的内容是原创就可以了,为了保持文章的字数达到300字原创,自己也是不得不在凑字数。