Skip to content

Commit 71454b4

Browse files
draft
1 parent 5c9e988 commit 71454b4

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package easy;
2+
3+
import java.util.HashSet;
4+
import java.util.Iterator;
5+
import java.util.Set;
6+
7+
/**349. Intersection of Two Arrays QuestionEditorial Solution My Submissions
8+
Total Accepted: 37539
9+
Total Submissions: 84405
10+
Difficulty: Easy
11+
Given two arrays, write a function to compute their intersection.
12+
13+
Example:
14+
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
15+
16+
Note:
17+
Each element in the result must be unique.
18+
The result can be in any order.*/
19+
public class IntersectionOfTwoArrays {
20+
21+
//then I clicked its Tags, and find it's marked with so many tags: Binary Search, HashTable, Two Pointers, Sort, now I'll try to do it one by one
22+
23+
24+
//so naturally, I come up with this naive O(n^2) solution and surprisingly it got AC'ed immediately, no wonder it's marked as EASY.
25+
public int[] intersection_naive(int[] nums1, int[] nums2) {
26+
Set<Integer> set = new HashSet();
27+
for(int i = 0; i < nums1.length; i++){
28+
for(int j = 0; j < nums2.length; j++){
29+
if(nums1[i] == nums2[j]) set.add(nums1[i]);
30+
}
31+
}
32+
int[] result = new int[set.size()];
33+
Iterator<Integer> it = set.iterator();
34+
int i = 0;
35+
while(it.hasNext()){
36+
result[i++] = it.next();
37+
}
38+
return result;
39+
}
40+
41+
}

0 commit comments

Comments
 (0)