|
| 1 | +packageeasy; |
| 2 | + |
| 3 | +importjava.util.HashSet; |
| 4 | +importjava.util.Iterator; |
| 5 | +importjava.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 | +publicclassIntersectionOfTwoArrays { |
| 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 | +publicint[]intersection_naive(int[]nums1,int[]nums2) { |
| 26 | +Set<Integer>set =newHashSet(); |
| 27 | +for(inti =0;i <nums1.length;i++){ |
| 28 | +for(intj =0;j <nums2.length;j++){ |
| 29 | +if(nums1[i] ==nums2[j])set.add(nums1[i]); |
| 30 | + } |
| 31 | + } |
| 32 | +int[]result =newint[set.size()]; |
| 33 | +Iterator<Integer>it =set.iterator(); |
| 34 | +inti =0; |
| 35 | +while(it.hasNext()){ |
| 36 | +result[i++] =it.next(); |
| 37 | + } |
| 38 | +returnresult; |
| 39 | + } |
| 40 | + |
| 41 | +} |