一、問題介紹
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]
二、解題思路
nums1轉爲換unordered_set,然後遍歷nums,如果在set中有相同的元素,則push_back到temp中(temp爲結果vector)
三、代碼實現
#include<unordered_set>
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> result;
//vector轉set,避免重複
unordered_set<int> set(nums1.begin(), nums1.end());
for(int& i:nums2){
if(set.count(i)){
result.push_back(i);
//i已經找到了,那就在set中刪除掉,防止後面出現時又重複push_back到result中
set.erase(i);
}
}
return result;
}
};