https://leetcode.com/problems/intersection-of-two-arrays-ii/description/
Solution 1. Use a map
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
unordered_map<int,int> cnt;
for(int i=0; i<nums1.size(); i++) {
cnt[nums1[i]]++;
}
for(int j=0; j<nums2.size(); j++) {
if(cnt[nums2[j]]-- > 0) res.push_back(nums2[j]);
}
return res;
}
Solution 2.
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> res;
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
for(int i=0, j=0; i<nums1.size()&&j<nums2.size();) {
if(nums1[i] == nums2[j]) {
res.push_back(nums1[i]);
i++;
j++;
}
else if(nums1[i]<nums2[j]) i++;
else j++;
}
return res;
}
No comments:
Post a Comment