标签:What ctr Arrays res Two II vector nums1 nums2
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to nums2's size? Which algorithm is better?
- What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
1 // class Solution { 2 // public: 3 // vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { 4 // unordered_map<int, int> ctr; 5 // vector<int> res; 6 // for (auto i : nums1) ctr[i]++; 7 // for (auto i : nums2) { 8 // if (ctr.count(i) > 0 && ctr[i] > 0) { 9 // ctr[i]--; 10 // res.push_back(i); 11 // } 12 // } 13 // return res; 14 // } 15 // }; 16 17 class Solution { 18 public: 19 vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { 20 vector<int> res; 21 22 sort(nums1.begin(), nums1.end()); 23 sort(nums2.begin(), nums2.end()); 24 25 int i1 = 0, i2 = 0; 26 while(i1<nums1.size() && i2<nums2.size()){ 27 if(nums1[i1] == nums2[i2]){ 28 res.push_back(nums1[i1]); 29 i1++; 30 i2++; 31 } 32 else if(nums1[i1] < nums2[i2]){ 33 i1++; 34 } 35 else{ 36 i2++; 37 } 38 } 39 40 return res; 41 } 42 };
标签:What,ctr,Arrays,res,Two,II,vector,nums1,nums2 来源: https://www.cnblogs.com/qinduanyinghua/p/11531836.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。