Given the arrays, write a function to compute their intersection.
Notice
Each element in the result must is unique.
The result can be on any order.
Has you met this question in a real interview?
Example
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Challenge
Can you implement it in three different algorithms?
Leetcode on the original topic, please see my previous blog intersection of the Arrays.
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) { Set<int>s, Res; for(Auto a:nums1) S.insert (a); for(Auto a:nums2) {if(S.count (a)) Res.insert (a); } returnvector<int>(Res.begin (), Res.end ()); }};
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 { if(Res.empty () | | Res.back ()! =Nums1[i]) {Res.push_back (nums1[i]); } ++i; ++J; } } returnRes; }};
Solution Three:
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) { Set<int>Res; Sort (Nums2.begin (), Nums2.end ()); for(Auto a:nums1) {if(BinarySearch (NUMS2, a)) {Res.insert (a); } } returnvector<int>(Res.begin (), Res.end ()); } BOOLBinarySearch (vector<int> &nums,inttarget) { intleft =0, right =nums.size (); while(Left <Right ) { intMid = left + (right-left)/2; if(Nums[mid] = = target)return true; Else if(Nums[mid] < target) left = mid +1; Elseright =mid; } return false; }};
Solution Four:
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) { Set<int>S1 (Nums1.begin (), Nums1.end ()), S2 (Nums2.begin (), Nums2.end ()), res; Set_intersection (S1.begin (), S1.end (), S2.begin (), S2.end (), Inserter (res, Res.begin ())); returnvector<int>(Res.begin (), Res.end ()); }};
[Lintcode] Intersection of two Arrays two arrays intersect