Skip to content

added intersectionOfTwoArrays #109

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 20, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ LeetCode

| # | Title | Solution | Difficulty |
|---| ----- | -------- | ---------- |
|349|[Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/) | [C++](./algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp)|Easy|
|347|[Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements/) | [C++](./algorithms/cpp/topKFrequentElements/topKFrequentElements.cpp)|Medium|
|345|[Reverse Vowels of a String](https://leetcode.com/problems/reverse-vowels-of-a-string/) | [C++](./algorithms/cpp/reverseVowelsOfAString/reverseVowelsOfAString.cpp)|Easy|
|337|[House Robber III](https://leetcode.com/problems/house-robber-iii/) | [C++](./algorithms/cpp/houseRobber/houseRobberIII.cpp)|Medium|
Expand Down
31 changes: 31 additions & 0 deletions algorithms/cpp/intersectionOfTwoArrays/intersectionOfTwoArrays.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Source : https://leetcode.com/problems/intersection-of-two-arrays/
// Author : Calinescu Valentin
// Date : 2016-05-20

/***************************************************************************************
*
* 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.
*
***************************************************************************************/
class Solution {
public:
set <int> inter1, inter2;//we use sets so as to avoid duplicates
vector <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 sorted
for(int i = 0; i < nums2.size(); i++)
if(inter1.find(nums2[i]) != inter1.end())//search nums1 in O(logN)
inter2.insert(nums2[i]);//populate the intersection set
for(set<int>::iterator it = inter2.begin(); it != inter2.end(); ++it)
solution.push_back(*it);//copy the set into a vector
return solution;
}
};