leetcode| Intersection of Arrays

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.