Find Common Elements Between Two Arrays
Intuition\nTo find the intersection of two arrays, our initial thought is to compare each element of the first array with each element of the second array. If a
# Intuition\nTo find the intersection of two arrays, our initial thought is to compare each element of the first array with each element of the second array. If a match is found, we count it as part of the intersection.\n\n# Approach\n1. Initialize two counters, `ans1` and `ans2`, to zero. These counters will keep track of the number of intersections found from `nums1` in `nums2` and from `nums2` in `nums1` respectively.\n2. Use a nested loop to compare each element of `nums1` with every element of `nums2`. If a match is found, increment `ans1` and break the inner loop to avoid counting duplicates.\n3. Use another nested loop to compare each element of `nums2` with every element of `nums1`. If a match is found, increment `ans2` and break the inner loop.\n4. Return the counts `ans1` and `ans2` in an array.\n\n# Complexity\n- **Time complexity**:\n  The time complexity of this approach is (O(m times n)), where (m) is the length of `nums1` and (n) is the length of `nums2`. This is because each element in `nums1` is compared with each element in `nums2`, and vice versa.\n\n- **Space complexity**:\n  The space complexity is (O(1)) since we are only using a fixed amount of extra space for the counters and the result array.\n\n# Code\n\n```java\nclass Solution {\n    public int[] findIntersectionValues(int[] nums1, int[] nums2) {\n        int ans1 = 0;\n        int ans2 = 0;\n        // Loop to count intersections from nums1 in nums2\n        for (int i = 0; i < nums1.length; i++) {\n            for (int j = 0; j < nums2.length; j++) {\n                if (nums1[i] == nums2[j]) {\n                    ans1++;\n                    break;\n                }\n            }\n        }\n        // Loop to count intersections from nums2 in nums1\n        for (int i = 0; i < nums2.length; i++) {\n            for (int j = 0; j < nums1.length; j++) {\n                if (nums2[i] == nums1[j]) {\n                    ans2++;\n                    break;\n                }\n            }\n        }\n        // Return the counts in an array\n        return new int[] {ans1, ans2};\n    }\n}\n```\n\n# Notes\n- This implementation will count an element multiple times if it appears more than once in both arrays.\n- The order of the input arrays matters in the sense that `ans1` counts intersections from `nums1` in `nums2`, and `ans2` counts intersections from `nums2` in `nums1`.\n- If we need to avoid counting duplicates or improve efficiency, we could use sets or hash maps, but that would require changes to the code.
['Array', 'Hash Table', 'Java']