Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
Note:
- Each element in the result must be unique.
- The result can be in any order.
想法:先找出两个vector中相等的元素,放入另外一个vector中。然后去掉重复元素
注意:vector中的成员函数unique()只是去除相邻的重复元素,因而需要对vector内部的元素进行排序。但是当执行unique()函数后,去除的重复元素仍然存在,因而需要使用erase()完全去除尾部的元素。
class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> result; for(int i = 0 ; i < nums1.size() ; i++){ for(int j = 0;j<nums2.size() ; j++){ if(nums1.at(i) == nums2.at(j)){ result.push_back(nums1[i]); } } } sort(result.begin(),result.end()); result.erase(unique(result.begin(), result.end()), result.end()); return result; } };