2
头图

The intersection of two arrays

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

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/intersection-of-two-arrays/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: array traversal
  • First put all the numbers in nums1 into firstNums in Set;
  • Then initialize a result array to put the final result, and declare a Set as secondNums to put the repeated elements of nums2 and nums1, and then traverse nums2;
  • If firstNums exists and secondNums does not exist, put the current number in result and put it in secondNums.
  • After the traversal is complete, all numbers in the 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 + " ");
        }
    }
}
[Daily Message] The most dazzling light in the world is the appearance of your hard work besides the sun.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!