Skip to content

Commit 7dfded0

Browse files
Intersection of Two Arrays
1 parent 67154ad commit 7dfded0

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package leetcode.easy;
2+
3+
import java.util.ArrayList;
4+
import java.util.HashMap;
5+
6+
/**
7+
* https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
8+
* <p>
9+
* Example 1:
10+
* Input: nums1 = [1,2,2,1], nums2 = [2,2]
11+
* Output: [2,2]
12+
* <p>
13+
* Example 2:
14+
* Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
15+
* Output: [4,9]
16+
*/
17+
public class IntersectionOfTwoArrays {
18+
19+
public static void main(String[] args) {
20+
// Test case 1
21+
int[] nums1 = {1, 2, 2, 1};
22+
int[] nums2 = {2, 2};
23+
int[] result1 = intersect(nums1, nums2);
24+
System.out.print("Intersection of nums1 and nums2: ");
25+
for (int num : result1) {
26+
System.out.print(num + " ");
27+
}
28+
System.out.println();
29+
30+
// Test case 2
31+
int[] nums3 = {4, 9, 5};
32+
int[] nums4 = {9, 4, 9, 8, 4};
33+
int[] result2 = intersect(nums3, nums4);
34+
System.out.print("Intersection of nums3 and nums4: ");
35+
for (int num : result2) {
36+
System.out.print(num + " ");
37+
}
38+
System.out.println();
39+
}
40+
41+
public static int[] intersect(int[] nums1, int[] nums2) {
42+
HashMap<Integer, Integer> map = new HashMap<>();
43+
ArrayList<Integer> resultList = new ArrayList<>();
44+
45+
// Count frequency of each element in nums1
46+
for (int num : nums1) {
47+
map.put(num, map.getOrDefault(num, 0) + 1);
48+
}
49+
50+
// Find intersection with nums2
51+
for (int num : nums2) {
52+
if (map.containsKey(num) && map.get(num) > 0) {
53+
resultList.add(num);
54+
map.put(num, map.get(num) - 1); // Decrease the count in the map
55+
}
56+
}
57+
58+
// Convert ArrayList to int array
59+
int[] result = new int[resultList.size()];
60+
for (int i = 0; i < resultList.size(); i++) {
61+
result[i] = resultList.get(i);
62+
}
63+
64+
return result;
65+
}
66+
}

0 commit comments

Comments
 (0)