Leetcode 350. Intersection of Arrays II

Source: Internet
Author: User

Intersection of Arrays II
    • Total accepted:23510
    • Total submissions:56283
    • Difficulty:easy

Given the arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1] , nums2 = [2, 2] , return [2, 2] .

Note:

    • Each element of the result should appear as many times as it shows in both arrays.
    • The result can be on any order.

Follow up:

    • What if the given array is already sorted? How would optimize your algorithm?
    • What if nums1' s size is small compared to nums2' s size? Which algorithm is better?
    • What if elements of nums2 be stored on disk, and the memory is limited such so you cannot load all elements in To the memory at once?

Idea: and Leetcode 349. Intersection of the arrays similar, but note the difference of the return value.

In addition, I learned the usage of unordered_set and unordered_map .

Code:

Method One: Using Unordered_map, the complexity is lower than the method two.

1 classSolution {2  Public:3vector<int> Intersect (vector<int>& Nums1, vector<int>&nums2) {4unordered_map<int,int>m;5vector<int>Res;6          for(intI:NUMS1) m[i]++;7          for(inti:nums2) {8             if(m[i]-->0){9 Res.push_back (i);Ten             } One         } A         returnRes; -     } -};

Method Two:

1 classSolution {2  Public:3vector<int> Intersect (vector<int>& Nums1, vector<int>&nums2) {4 sort (Nums1.begin (), Nums1.end ());5 sort (Nums2.begin (), Nums2.end ());6vector<int>Res;7         intI=0, j=0;8          while(I<nums1.size () &&j<nums2.size ()) {9             //while (I+1<nums1.size () &&nums1[i]==nums1[i+1]) i++;//Remove duplicate elementsTen             //while (J+1<nums2.size () &&nums2[j]==nums2[j+1]) j + +; One             if(nums1[i]==Nums2[j]) { A Res.push_back (Nums2[j]); -i++; -J + +; the             } -             Else{ -nums1[i]>nums2[j]?j++:i++; -             } +         } -         returnRes; +     } A};

Leetcode 350. Intersection of Arrays II

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.