Untitled

 avatar
unknown
plain_text
2 months ago
1.1 kB
4
Indexable
import java.util.*;

public class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> set = new HashSet<>();
        List<Integer> result = new ArrayList<>();

        // Add all elements of nums1 to the set
        for (int num : nums1) {
            set.add(num);
        }

        // Check for intersection with nums2
        for (int num : nums2) {
            if (set.contains(num)) {
                result.add(num);
                set.remove(num); // Remove to ensure unique elements
            }
        }

        // Convert result list to array
        return result.stream().mapToInt(i -> i).toArray();
    }

    public static void main(String[] args) {
        Solution solution = new Solution();

        int[] nums1 = {1, 2, 2, 1};
        int[] nums2 = {2, 2};
        System.out.println(Arrays.toString(solution.intersection(nums1, nums2))); // Output: [2]

        int[] nums3 = {4, 9, 5};
        int[] nums4 = {9, 4, 9, 8, 4};
        System.out.println(Arrays.toString(solution.intersection(nums3, nums4))); // Output: [9, 4]
    }
}
Editor is loading...
Leave a Comment