1. 程式人生 > >[Leetcode] 349. Intersection of Two Arrays

[Leetcode] 349. Intersection of Two Arrays

Description:
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.

Language: C++

解法一:
由於題目是“存不存在問題”而不是“關聯對應問題”(如重複元素出現幾次),想到用set來解決。其中像set中插入元素用insert。且容器類的建構函式有相同介面,因此可以很輕鬆吧set型別轉換為vector型別。
Time:

O(nlogn)
Space: O(n)

class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {

        set<int> record(nums1.begin(),nums1.end());

        set<int> result;

        for(int i = 0; i < nums2.size(); i++){

            if
(record.find(nums2[i])!=record.end()) result.insert(nums2[i]); } vector<int> res(result.begin(),result.end()); return res; } };