Leetcode 350. Intersection of Two Arrays II
来源:互联网 发布:jquery.base64.js用法 编辑:程序博客网 时间:2024/05/21 17:30
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Hash table solution: Time: O(m + n) Space: O(m + n)
class Solution {public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> dict; vector<int> res; for(int i = 0; i < (int)nums1.size(); i++) dict[nums1[i]]++; for(int i = 0; i < (int)nums2.size(); i++) if(--dict[nums2[i]] >= 0) res.push_back(nums2[i]); return res; }};
Hash table solution2: Time: O(m + n) Space: O(m)
class Solution {public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { unordered_map<int, int> dict; vector<int> res; for(int i = 0; i < (int)nums1.size(); i++) dict[nums1[i]]++; for(int i = 0; i < (int)nums2.size(); i++) if(dict.find(nums2[i]) != dict.end() && --dict[nums2[i]] >= 0) res.push_back(nums2[i]); return res; }};
Sort and two pointers Solution: Time: O(max(m, n) log(max(m, n))) Space: O(m + n)
class Solution {public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); int n1 = (int)nums1.size(), n2 = (int)nums2.size(); int i1 = 0, i2 = 0; vector<int> res; while(i1 < n1 && i2 < n2){ if(nums1[i1] == nums2[i2]) { res.push_back(nums1[i1]); i1++; i2++; } else if(nums1[i1] > nums2[i2]){ i2++; } else{ i1++; } } return res; }};
0 0
- LeetCode 350. Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- [Leetcode] 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- LeetCode - 350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- leetcode-350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- [leetcode]350. Intersection of Two Arrays II
- HDU 5696 区间的价值 (百度之星2B)
- 欢迎使用CSDN-markdown编辑器
- HDU-1856-More is better
- Plist存储简述
- SpringFramework的几个核心模块
- Leetcode 350. Intersection of Two Arrays II
- 框架 day37 Spring3,AOP,代理模式(动态/CGLIB/工厂bean),传统AOP,AspectJ框架(基于xml/注解),切入点表达式,jdbcTemplate
- 理解 Java 垃圾回收机制
- 食物链
- hdu 4114 状压dp floyd
- 第八周项目:指向学生类的指针
- java基础(一)
- 最近公共祖先
- 第七届 科技节 电子设计大赛 一等奖作品---智慧生态园