package com.zmz.algorithm.hashtable;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;

/**
 * @author 张明泽
 * Create by 2022/5/30 16:46
 * 两个数组的交集
 * LeetCode-349
 */
public class IntersectionArrays {
    public static void main(String[] args) {
        int[] nums1 = {4,9,5};
        int[] nums2 = {9,4,9,8,4};
        int[] result = intersection(nums1,nums2);
        System.out.println(Arrays.toString(result));
    }
    public static int[] intersection(int[] nums1, int[] nums2) {
        HashSet<Integer> hashSet = new HashSet<>();
        HashSet<Integer> result = new HashSet<>();
        for (int i = 0; i < nums1.length; i++) {
            hashSet.add(nums1[i]);
        }
        for (int i = 0; i < nums2.length; i++) {
            if (hashSet.contains(nums2[i])) {
                result.add(nums2[i]);
            }
        }
        int[] res = new int[result.size()];
        int index = 0;
        for (Integer integer : result) {
            res[index++] = integer;
        }
        return res;
    }
}
最后修改:2022 年 06 月 02 日 10 : 00 AM
赏杯咖啡喝 谢谢您~