Given two arrays, write a function to compute their intersection.
Example:
Given nums1 =
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.
Solution :
The idea to solve this problem is quite simple. We can just move all the elements of nums1 to one
container then check every element in nums2 to derive the result. Noted that the result should not
contain duplicate values. So we can use SET in STL to accomplish this work since the set will ignore
the duplicate values when adding new elements into it.
- class Solution {
- public:
- vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
- set<int> SET (nums1.begin(),nums1.end());
- set<int> result;
- for(auto i:nums2)
- if(SET.count(i)) result.insert(i);
- return vector<int>(result.begin(), result.end());
- }
- };
0 意見:
張貼留言