Intersection of Two Arrays Solutions in C++
Number 349
Difficulty Easy
Acceptance 62.6%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/intersection-of-two-arrays/// Author : Calinescu Valentin, Hao Chen// Date : 2016-05-20class Solution {public:set <int> inter1, inter2;//we use sets so as to avoid duplicatesvector <int> solution;vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {for(int i = 0; i < nums1.size(); i++)inter1.insert(nums1[i]);//get all of the unique elements in nums1 sortedfor(int i = 0; i < nums2.size(); i++)if(inter1.find(nums2[i]) != inter1.end())//search inter1 in O(logN)inter2.insert(nums2[i]);//populate the intersection setfor(set<int>::iterator it = inter2.begin(); it != inter2.end(); ++it)solution.push_back(*it);//copy the set into a vectorreturn solution;}};/** This Solution use one unordered_set*/class Solution2 {public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {unordered_set<int> hash_set(nums1.begin(), nums1.end());vector<int> res ;for (auto it& : nums2) {if (hash_set.count(it)) {res.push_back(it);hash_set.erase(it);}}return res;}};/** This Solution use unordered_map, insert the data into a map is more efficent than set*/class Solution {public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {unordered_map<int, bool> m;for (auto n : nums1) {m[n] = true;}vector<int> result;for (auto n : nums2){if (m.find(n) != m.end() && m[n] ){result.push_back(n);m[n]=false;}}return result;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/intersection-of-two-arrays/description//// Author : liuyubobobo/// Time : 2017-07-12#include <iostream>#include <vector>#include <unordered_set>using namespace std;/// Hash Set/// Time complexity: O(len(nums1) + len(nums2))/// Space Complexity: O(len(nums1))class Solution {public:vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {unordered_set<int> record(nums1.begin(), nums1.end());unordered_set<int> resultSet;for( int i = 0 ; i < nums2.size() ; i ++ )if( record.find(nums2[i]) != record.end() )resultSet.insert( nums2[i] );return vector<int>(resultSet.begin(), resultSet.end());}};void printVec(const vector<int>& vec){for(int e: vec)cout << e << " ";cout << endl;}int main() {int nums1[] = {1, 2, 2, 1};vector<int> vec1(nums1, nums1 + sizeof(nums1)/sizeof(int));int nums2[] = {2, 2};vector<int> vec2(nums2, nums2 + sizeof(nums2)/sizeof(int));printVec(Solution().intersection(vec1, vec2));return 0;}