求两个数组的交集

import java.util.HashSet;

/**
 * 349. Intersection of Two Arrays
 * Given two arrays, write a function to compute their intersection.
 *
 * Example 1:
 *
 * Input: nums1 = [1,2,2,1], nums2 = [2,2]
 * Output: [2]
 */


public class Solution {
    /**target:获取两个数组中重复的元素
     * 1 将对一个数组中元素放入set1中
     * 2 遍历第二个数组 将相同元素加入resultSet中
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        HashSet set = new HashSet<>();

        for (int i = 0; i < nums1.length; i++) {
            set.add(nums1[i]);
        }

        HashSet resultSet = new HashSet<>();

        for (int i = 0; i < nums2.length; i++) {
            if (set.contains(nums2[i])) {
                resultSet.add(nums2[i]);
            }
        }

        int[] resultArr = new int[resultSet.size()];

        int index = 0;
        for (Integer num : resultSet) {
            resultArr[index ++] = num;
        }

        return resultArr;

    }
}

你可能感兴趣的:(求两个数组的交集)