目标:
输入两个数组,输出它们的交集。
思路:
用一个set来保存结果,遍历数组一中的元素是否数组二中存在。
代码:
1 class Solution { 2 public: 3 vector intersection(vector & nums1, vector & nums2) { 4 set result; 5 for (int i = 0; i < nums1.size(); i++) { 6 for (int j = 0; j < nums2.size(); j++) { 7 if (nums1[i] == nums2[j]) { 8 result.insert(nums1[i]); 9 break;10 }11 }12 }13 vector v(result.begin(), result.end());14 return v;15 }16 };