博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LintCode] Intersection of Two Arrays II 两个数组相交之二
阅读量:6856 次
发布时间:2019-06-26

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

 

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

Notice
    Each element in the result should appear as many times as it shows in both arrays.
    The result can be in any order.
Example
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Challenge
    What if the given array is already sorted? How would you optimize your algorithm?
    What if nums1's size is small compared to num2'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?

 

LeetCode上的原题,请参见我之前的博客。

 

解法一:

class Solution {public:    /**     * @param nums1 an integer array     * @param nums2 an integer array     * @return an integer array     */    vector
intersection(vector
& nums1, vector
& nums2) { vector
res; unordered_map
m; for (auto a : nums1) ++m[a]; for (auto a : nums2) { if (m[a] > 0) { res.push_back(a); --m[a]; } } return res; }};

 

解法二:

class Solution {public:    /**     * @param nums1 an integer array     * @param nums2 an integer array     * @return an integer array     */    vector
intersection(vector
& nums1, vector
& nums2) { vector
res; int i = 0, j = 0; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); while (i < nums1.size() && j < nums2.size()) { if (nums1[i] < nums2[j]) ++i; else if (nums1[i] > nums2[j]) ++j; else { res.push_back(nums1[i]); ++i; ++j; } } return res; }};

 

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

你可能感兴趣的文章
Exchange 2013 PowerShell创建自定义对象
查看>>
RAID-10 阵列的创建(软)
查看>>
javaScript的调试(四)
查看>>
nginx不使用正则表达式匹配
查看>>
利用putty进行vnc + ssh tunneling登录
查看>>
hadoop1.x作业提交过程分析(源码分析第二篇)
查看>>
默认安装vsftpd后
查看>>
《Redis设计与实现》读书笔记
查看>>
waiting for changelog lock.
查看>>
小白学爬虫-批量部署Splash负载集群
查看>>
你离BAT之间,只差这一套Java面试题
查看>>
laravel package 推荐,数据备份
查看>>
Synchronized锁在Spring事务管理下,为啥还线程不安全?
查看>>
环境变量PATH cp命令 mv命令 文档查看cat/more/less/head/tail
查看>>
阿里云亮相2019联通合作伙伴大会,边缘计算等3款云产品助力5G时代产业数字化转型...
查看>>
dubbo源码分析-服务端发布流程-笔记
查看>>
阿里云发布Apsara SA系列混合云存储阵列
查看>>
GoJS教程:链接模版
查看>>
QListWidget方式显示缩略图
查看>>
金三银四:蚂蚁金服JAVA后端面试题及答案之二面
查看>>