题目大意:求2个数组的交集。
Problem:
https://leetcode.com/problems/intersection-of-two-arrays/description/
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
Note:
- Each element in the result must be unique.
- The result can be in any order.
C++ using std::set_intersection
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Author: Huahua // Running time: 8 ms class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> intersection(max(nums1.size(), nums2.size())); std::sort(nums1.begin(), nums1.end()); std::sort(nums2.begin(), nums2.end()); // Inputs must be in ascending order auto it = std::set_intersection(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), intersection.begin()); intersection.resize(it - intersection.begin()); std::set<int> s(intersection.begin(), intersection.end()); return vector<int>(s.begin(), s.end()); } }; |
C++ hashtable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Author: Huahua // Running time: 7 ms class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_set<int> m(nums1.begin(), nums1.end()); vector<int> ans; for (int num : nums2) { if (!m.count(num)) continue; ans.push_back(num); m.erase(num); } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment