LeetCode#349 Intersection of Two Arrays
来源:互联网 发布:支持ubuntu的手机 编辑:程序博客网 时间:2024/06/07 22:07
key: map–find & count
Runtime: 16 ms / beats 19.77%
No reference
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { vector<int> res; map<int, int> map1, map2, mapInset; for(int i = 0; i < nums1.size(); i++) { map<int, int>::iterator iter; iter = map1.find(nums1[i]); if(iter == map1.end()) { map1.insert(pair<int, int>(nums1[i],1)); } else iter->second++; } for(int i = 0; i < nums2.size(); i++) { // map<int, int>::iterator iter; // iter = map1.find(nums2[i]); int cnt1 = map1.count(nums2[i]); // if(iter == map1.end()) continue; if(cnt1 == 0) continue; else { // map<int, int>::iterator iter2; // iter2 = mapInset.find(nums2[i]); int cnt2 = mapInset.count(nums2[i]); //if(iter == mapInset.end()) if(cnt2 == 0) { mapInset.insert(pair<int, int>(nums2[i],1)); res.push_back(nums2[i]); } else continue; } } return res; }};
Update: unordered set & for range
Runtime: 8 ms / beats 85.44%
Reference: discuss
class Solution {public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2) { unordered_set<int> set1(nums1.begin(), nums1.end()); vector<int> res; for(auto iter : nums2) { if(set1.count(iter)) { res.push_back(iter); set1.erase(iter); } } return res; }};
0 0
- Leetcode-349 Intersection of Two Arrays
- leetcode 349 Intersection of Two Arrays C++
- LeetCode 349 Intersection of Two Arrays
- LeetCode-349&350.Intersection of Two Arrays
- LeetCode-349 Intersection of Two Arrays
- leetcode-Intersection of Two Arrays-349
- LeetCode 349 Intersection of Two Arrays
- LeetCode#349 Intersection of Two Arrays
- LeetCode(349)Intersection of Two Arrays
- [LeetCode]349 Intersection of Two Arrays
- [LeetCode-349] Intersection of Two Arrays(java)
- Leetcode 349 Intersection of Two Arrays
- LeetCode No.349 Intersection of Two Arrays
- leetcode-349-Intersection of Two Arrays
- [Leetcode 349]Intersection of Two Arrays
- leetcode 349 Intersection of Two Arrays
- Leetcode #349 Intersection of Two Arrays
- LeetCode 349 Intersection of Two Arrays
- 友盟社会化组件iOS版使用评测
- 无需Flash无需依赖任何JS库实现文本复制与剪切
- linux kernel编译生成zImage过程详解
- Entity Framework Code First模式基础知识及入门实例01
- 机器学习推荐论文书籍
- LeetCode#349 Intersection of Two Arrays
- Twisted-Factory和Protocol类的分工
- 使用Linux top命令进行性能分析
- new(std::nothrow) 和 new
- 设计模式总结之Composite Pattern(组合模式)
- 自定义 Android 对话框 (AlertDialog) 的样式
- XML在Android-iOS上的应用
- Java SWT 文本框 垂直 居中
- 导入*.sql脚本