[Lintcode] Intersection of two Arrays II two arrays intersect the second

Source: Internet
Author: User
Tags lintcode

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

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

Example

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Challenge

What if the given array is already sorted? How would optimize your algorithm?
What if Nums1 ' s size is small compared to num2 ' 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 into the ME Mory at once?

Leetcode on the original topic, see my previous blog intersection of Arrays Ii.

Solution One:

classSolution { Public:    /** * @param nums1 an integer array * @param nums2 a integer array * @return an integer array*/Vector<int> Intersection (vector<int>& Nums1, vector<int>&nums2) {Vector<int>Res; Unordered_map<int,int>m;  for(auto a:nums1) + +M[a];  for(Auto a:nums2) {if(M[a] >0) {res.push_back (a); --M[a]; }        }        returnRes; }};

Solution Two:

classSolution { Public:    /** * @param nums1 an integer array * @param nums2 a integer array * @return an integer array*/Vector<int> Intersection (vector<int>& Nums1, vector<int>&nums2) {Vector<int>Res; inti =0, j =0;        Sort (Nums1.begin (), Nums1.end ());        Sort (Nums2.begin (), Nums2.end ());  while(I < Nums1.size () && J <nums2.size ()) {            if(Nums1[i] < Nums2[j]) + +i; Else if(Nums1[i] > Nums2[j]) + +J; Else{res.push_back (nums1[i]); ++i; ++J; }        }        returnRes; }};

[Lintcode] Intersection of two Arrays II two arrays intersect the second

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.