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.
給定兩個數組,計算它們的重復部分。
注意:返回結果中的元素不要重復,結果可以任意順序組織。
思路:
利用關聯容器set保存nums1的元素,對于nums2中的每個元素,檢查是否在set中。
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
unordered_set<int> m(nums1.begin(), nums1.end());
vector<int> res;
for (auto a : nums2)
if (m.count(a)) { //元素重復
res.push_back(a);
m.erase(a); //已經計入的不再重復計算
}
return res;
}
};
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for(int i=0;i<nums1.length;i++){
set1.add(nums1[i]);
}
for(int i=0;i<nums2.length;i++){
if(set1.contains(nums2[i])) set2.add(nums2[i]);
}
int[] res=new int[set2.size()];
int i=0;
for(int num:set2){
res[i++]=num;
}
return res;
}
}