Skip to content

Commit a61701e

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 350_Intersection_of_Two_Arrays_II.java
1 parent cfe312e commit a61701e

File tree

1 file changed

+22
-14
lines changed

1 file changed

+22
-14
lines changed
Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,34 @@
11
class Solution {
22
public int[] intersect(int[] nums1, int[] nums2) {
3-
HashMap<Integer, Integer> hm = new HashMap<>();
4-
ArrayList<Integer> intersection = new ArrayList<>();
3+
if (nums1 == null || nums2 == null) {
4+
return new int[0];
5+
}
56

6-
for (int i = 0; i < nums1.length; i++) {
7-
hm.put(nums1[i], hm.getOrDefault(nums1[i], 0) + 1);
7+
if (nums2.length > nums1.length) {
8+
return intersect(nums2, nums1);
89
}
910

10-
for (int i = 0; i < nums2.length; i++) {
11-
int freq = hm.getOrDefault(nums2[i], 0);
12-
if (freq > 0) {
13-
intersection.add(nums2[i]);
14-
hm.put(nums2[i], --freq);
11+
Map<Integer, Integer> map = new HashMap<>();
12+
List<Integer> result = new ArrayList<>();
13+
14+
for (int num : nums2) {
15+
map.put(num, map.getOrDefault(num, 0) + 1);
16+
}
17+
18+
for (int num : nums1) {
19+
int frequency = map.getOrDefault(num, 0);
20+
21+
if (frequency > 0) {
22+
result.add(num);
23+
map.put(num, frequency - 1);
1524
}
1625
}
1726

18-
int[] result = new int[intersection.size()];
19-
int idx = 0;
20-
for (int commonVal : intersection) {
21-
result[idx++] = commonVal;
27+
int[] arr = new int[result.size()];
28+
for (int i = 0; i < arr.length; i++) {
29+
arr[i] = result.get(i);
2230
}
2331

24-
return result;
32+
return arr;
2533
}
2634
}

0 commit comments

Comments
 (0)