Skip to content
Open
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
47 changes: 47 additions & 0 deletions Week2/349_Intersection_of_2_arrays.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
//if (nums1.size() > nums2.size()) return intersection(nums2, nums1);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is actually a very good idea :) Not sure why you commented it out.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because if their actual sizes are different it does not say anuthing about sizes of their unique arrays.
So I thought that this will give us profit only sometimes.


// The idea here is to use some hash table data structure (set or map).
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unordered_set is preferable. You don't wan't to use stuff that adds complexity and brings no value.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I also done this with unordered set first.
But with unordered set running time was slightly bigger I guess it is because of bigger hidden constant of operation erase in hset than operator [] in hmap.
https://leetcode.com/submissions/detail/80045924/

// This table shows the presense of element in first array.
// Then while traversing 2nd array we update answer if given element is present in table(first array),
// update table by removing current element.

vector<int> res;
unordered_map<int, bool> exist;
for (int i = 0; i < nums1.size(); ++i) {
exist[nums1[i]] = true;
}
for (int i = 0; i < nums2.size(); ++i) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't really need an index here. Just do - for(int num : nums2) {}

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok. This will make code more readable.

if (exist.find(nums2[i]) != exist.end() && exist[nums2[i]]) {
res.push_back(nums2[i]);
exist[nums2[i]] = false;
}
}
return res;
}
};

/*
nums1.size() = m, u - number of unique elements in nums1
nums2.size() = n
Time complexity T=O(max(m, n)) in average, worst case is T=O(m * max(m, n)).
Memory complexity M = O(u)

*/

/*
[]
[]

[1,2,3]
[]

[4]
[1,2,3]

[1,2,2,2,2,3,3,3,1]
[1,2,5]

*/