|
| 1 | +// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/ |
| 2 | +// Author : Calinescu Valentin |
| 3 | +// Date : 2016-05-22 |
| 4 | + |
| 5 | +/*************************************************************************************** |
| 6 | + * |
| 7 | + * Given two arrays, write a function to compute their intersection. |
| 8 | + * |
| 9 | + * Example: |
| 10 | + * Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2]. |
| 11 | + * |
| 12 | + * Note: |
| 13 | + * Each element in the result should appear as many times as it shows in both arrays. |
| 14 | + * The result can be in any order. |
| 15 | + * |
| 16 | + * Follow up: |
| 17 | + * What if the given array is already sorted? How would you optimize your algorithm? |
| 18 | + * What if nums1's size is small compared to num2's size? Which algorithm is better? |
| 19 | + * What if elements of nums2 are stored on disk, and the memory is limited such that you |
| 20 | + * cannot load all elements into the memory at once? |
| 21 | + * |
| 22 | + ***************************************************************************************/ |
| 23 | + |
| 24 | + /* Solution |
| 25 | + * -------- |
| 26 | + * |
| 27 | + * Follow up: |
| 28 | + * |
| 29 | + * 1)If the given array is already sorted we can skip the sorting. |
| 30 | + * |
| 31 | + * 2)If nums1 is significantly smaller than nums2 we can only sort nums1 and then binary |
| 32 | + * search every element of nums2 in nums1 with a total complexity of (MlogN) or if nums2 |
| 33 | + * is already sorted we can search every element of nums1 in nums2 in O(NlogM) |
| 34 | + * |
| 35 | + * 3)Just like 2), we can search for every element in nums2, thus having an online |
| 36 | + * algorithm. |
| 37 | + */ |
| 38 | + |
| 39 | +class Solution { // O(NlogN + MlogM) |
| 40 | +public: |
| 41 | + vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { |
| 42 | + sort(nums1.begin(), nums1.end());//we sort both vectors in order to intersect |
| 43 | + sort(nums2.begin(), nums2.end());//them later in O(N + M), where N = nums1.size() |
| 44 | + vector <int> solution; //M = nums2.size() |
| 45 | + int index = 0; |
| 46 | + bool finished = false; |
| 47 | + for(int i = 0; i < nums1.size() && !finished; i++) |
| 48 | + { |
| 49 | + while(index < nums2.size() && nums1[i] > nums2[index])//we skip over the |
| 50 | + index++;//smaller elements in nums2 |
| 51 | + if(index == nums2.size())//we have reached the end of nums2 so we have no more |
| 52 | + finished = true;//elements to add to the intersection |
| 53 | + else if(nums1[i] == nums2[index])//we found a common element |
| 54 | + { |
| 55 | + solution.push_back(nums1[i]); |
| 56 | + index++; |
| 57 | + } |
| 58 | + } |
| 59 | + return solution; |
| 60 | + } |
| 61 | +}; |
0 commit comments