349. Intersection of Two Arrays 數組交集

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;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容