Skip to content

Commit 0a63d93

Browse files
committed
Add Solution.java for 0349.Intersection of Two Arrays
1 parent ef387d9 commit 0a63d93

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Intersection of Two Arrays
2+
3+
Given two arrays, write a function to compute their intersection.
4+
5+
## Example 1:
6+
```
7+
Input: nums1 = [1,2,2,1], nums2 = [2,2]
8+
Output: [2]
9+
```
10+
11+
## Example 2:
12+
```
13+
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
14+
Output: [9,4]
15+
```
16+
Note:
17+
18+
* Each element in the result must be unique.
19+
* The result can be in any order.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
public int[] intersection(int[] nums1, int[] nums2) {
3+
HashSet<Integer> set1 = new HashSet<Integer>();
4+
for (Integer n : nums1) set1.add(n);
5+
HashSet<Integer> set2 = new HashSet<Integer>();
6+
for (Integer n : nums2) set2.add(n);
7+
8+
set1.retainAll(set2);
9+
10+
int [] output = new int[set1.size()];
11+
int idx = 0;
12+
for (int s : set1) output[idx++] = s;
13+
return output;
14+
}
15+
}

0 commit comments

Comments
 (0)