LeetCode-in-Java

2956. Find Common Elements Between Two Arrays

Easy

You are given two 0-indexed integer arrays nums1 and nums2 of sizes n and m, respectively.

Consider calculating the following values:

Return an integer array answer of size 2 containing the two values in the above order.

Example 1:

Input: nums1 = [4,3,2,3,1], nums2 = [2,2,5,2,3,6]

Output: [3,4]

Explanation: We calculate the values as follows:

Example 2:

Input: nums1 = [3,4,2,3], nums2 = [1,5]

Output: [0,0]

Explanation: There are no common elements between the two arrays, so the two values will be 0.

Constraints:

Solution

public class Solution {
    public int[] findIntersectionValues(int[] nums1, int[] nums2) {
        int[] freq2 = new int[101];
        int[] freq1 = new int[101];
        int[] ans = new int[2];
        for (int j : nums2) {
            freq2[j] = 1;
        }
        for (int j : nums1) {
            freq1[j] = 1;
            ans[0] = ans[0] + freq2[j];
        }
        for (int j : nums2) {
            ans[1] = ans[1] + freq1[j];
        }
        return ans;
    }
}