博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 350. Intersection of Two Arrays II
阅读量:6091 次
发布时间:2019-06-20

本文共 2716 字,大约阅读时间需要 9 分钟。

Description

Given two arrays, write a function to compute their intersection.

Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note:

Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

My solution

延续leetcode 344的思路,少做修改即可, 但是复杂度仍旧很高啊...

class Solution {public:    vector
intersect(vector
&nums1, vector
&nums2) { vector
res; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); int i = 0, j = 0; while (i < nums1.size() && j < nums2.size()) { if (nums1[i] < nums2[j]) ++i; else if (nums1[i] > nums2[j]) ++j; else { while (nums1[i] == nums2[j] && i < nums1.size() && j < nums2.size()) { res.push_back(nums1[i]); ++i; ++j; } while (nums1[i] == nums1[i - 1]) ++i; while (nums2[j] == nums2[j - 1]) ++j; } } return res; }};

Discuss

sort

Time: O(max(m, n) log(max(m, n)))

但我又不得不说, 同样是sort方式, 我的方案太丑!!

discuss中同样方法的代码如下:

class Solution {public:    vector
intersect(vector
& nums1, vector
& 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
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; }};

注意, 只用了一次while! 逻辑很清晰!

Hash table solution

Time: O(m + n) Space: O(m + n)

class Solution {public:    vector
intersect(vector
& nums1, vector
& nums2) { unordered_map
dict; vector
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; }};

采用unordered_map查询效率高, 无序.

Reference

转载地址:http://yvmwa.baihongyu.com/

你可能感兴趣的文章
nginx的中文rewrite规则
查看>>
GlusterFS安装配置
查看>>
log4j.properties配置详解(转载)
查看>>
css3常见的动画
查看>>
ubuntu16.04 改usb键盘的keycode.md
查看>>
flex组件拖拽
查看>>
python统计通过暴力破解尝试登陆本机的ip和次数
查看>>
linux下查看所有用户及所有用户组
查看>>
2012:Android关键而危险的“升级”之年
查看>>
HttpSessionListener接口监听网站在线人数
查看>>
spring事务属性的几个试验
查看>>
C#基础知识整理:C#基础(2)
查看>>
jQuery中attr和prop的区别
查看>>
Differences between Hub, Network Bridge, Switch and Router
查看>>
redmine如何添加qq邮箱功能
查看>>
Tsung参数说明【转载】
查看>>
solr学习(一)_solr4.2.0在tomcat6.0+win7上的部署
查看>>
redis sort
查看>>
iptables详解
查看>>
C语言学习笔记(五) 预处理符号
查看>>