Intersection of two arrays

Given two arrays, write a function to calculate their intersection.

Examples can be found on the LeetCode website.

Source: LeetCode link: leetcode-cn.com/problems/in… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Solution 1: array traversal
  • First put all the numbers in nums1 into the Set firstNums;
  • Then initialize a Result array to hold the final result and declare a Set as secondNums to hold the elements repeated by nums2 and nums1. Then iterate over nums2.
  • If firstNums exists and secondNums does not, place the current number into Result and secondNums.
  • When the loop is complete, all the numbers in Result are returned.
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class LeetCode_349 {
    public static int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> firstNums = new HashSet<>();
        for (int i : nums1) {
            firstNums.add(i);
        }
        int[] result = new int[nums1.length];
        int index = 0;
        Set<Integer> secondNums = new HashSet<>();
        for (int i : nums2) {
            if (firstNums.contains(i) && !secondNums.contains(i)) {
                secondNums.add(i);
                result[index++] = i;
            }
        }

        return Arrays.copyOfRange(result, 0, index);
    }

    public static void main(String[] args) {
        int[] nums1 = new int[] {1.2.2.1}, nums2 = new int[] {2.2};
        for (int i : intersection(nums1, nums2)) {
            System.out.print(i + ""); }}}Copy the code

The most dazzling light in the world in addition to the sun and the appearance of your efforts.