Given the arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must is unique.
- The result can be on any order.
Title: Find out the intersection of two arrays at a glance
Idea: My general idea is that the two arrays are first weighed separately, then an array is synthesized, the array is sorted, and the adjacent two elements in the array are the intersection elements, i.e. num[i] = = Num[i-1]
The code is a bit redundant, efficient,
Public int[] Intersection (int[] nums1, int[] nums2) {
Int len1 = nums1.length, Len2 = nums2.length, j = 0;
if (len1 = = 0 | | len2 = = 0) {
return new int[0];
}
Hashset<integer> Set1 = new hashset<integer> ();
Hashset<integer> Set2 = new hashset<integer> ();
hashset<integer> set3 = new hashset<integer> ();
for (int i = 0; i < len1; i++) {
Set1.add (nums1[i]);
}
for (int i = 0; i < len2; i++) {
Set2.add (nums2[i]);
}
Int[] temp = new Int[set1.size () + set2.size ()];
Iterator it1 = Set1.iterator ();
while (It1.hasnext ()) {
Temp[j++] = (Integer) it1.next ();
}
Iterator it2 = Set2.iterator ();
while (It2.hasnext ()) {
Temp[j++] = (Integer) it2.next ();
}
Arrays.sort (temp);
for (int i = 1; i < temp.length; i++) {
if (temp[i] = = Temp[i-1]) {
Set3.add (Temp[i]);
}
}
int res[] = new int[set3.size ()];
j = 0;
Iterator it3 = Set3.iterator ();
while (It3.hasnext ()) {
Res[j++] = (Integer) it3.next ();
}
return res;
}
leetcode| Intersection of Arrays