Back to course home
0% completed
Vote For New Content
We can a void a 3rd loop
Himaja Sree Tanneeru
Jan 17, 2025
Add num1 elements in set1, and while adding num2 elements, check if they exist in num1 and add only the intersection.
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { // Use a set to store elements from nums1 Set<Integer> set1 = new HashSet<>(); for (int num : nums1) { set1.add(num); } // Use another set to store the intersection Set<Integer> result = new HashSet<>(); for (int num : nums2) { if (set1.contains(num)) { result.add(num); // Add only if it exists in nums1 } } // Convert the result set to an array return result.stream().mapToInt(Integer::intValue).toArray(); } }
0
0
Comments
Comments
On this page