Monday, July 25, 2016

LeetCode [349] Intersection of Two Arrays

  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]
Note:
  • Each element in the result must be unique.
  • The result can be in any order.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        set<int> st(nums1.begin(), nums1.end());
        set<int> st1;
        for(auto n:nums2){
            if(st.count(n)) st1.insert(n);
        }
        vector<int> ret(st1.begin(), st1.end());
        return ret;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
    vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        sort(nums1.begin(), nums1.end());
        sort(nums2.begin(), nums2.end());
        vector<int> ret;
        int i=0, j = 0, n1 = nums1.size(), n2 = nums2.size();
        while(i<n1 && j<n2){
            if(nums1[i]<nums2[j]) i++;
            else if(nums1[i]>nums2[j]) j++;
            else{
                if(ret.empty() || ret.back()!=nums1[i]){
                    ret.push_back(nums1[i]);
                }
                i++;
                j++;
            }
        }
        return ret;
    }
};

No comments:

Post a Comment