当前位置:网站首页>Leetcode 笔记 350. 两个数组的交集 II
Leetcode 笔记 350. 两个数组的交集 II
2022-07-26 00:24:00 【Lyrig~】
题目描述
给你两个整数数组 nums1 和 nums2 ,请你以数组形式返回两数组的交集。返回结果中每个元素出现的次数,应与元素在两个数组中都出现的次数一致(如果出现次数不一致,则考虑取较小值)。可以不考虑输出结果的顺序。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2,2]
示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[4,9]
提示:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
进阶:
如果给定的数组已经排好序呢?你将如何优化你的算法?
如果 nums1 的大小比 nums2 小,哪种方法更优?
如果 nums2 的元素存储在磁盘上,内存是有限的,并且你不能一次加载所有的元素到内存中,你该怎么办?
思路
由于同一个数字在vector中可能出现不止一次,所以题目的本质其实就是,对每个数字在num1 和 num2 出现的次数做统计,最终每个数字,取其最小的那个。当然传统的暴力求解也是可以的,但是就没有这个题目的意义了。
这里针对思路前者,采用unordered_map进行对数字进行计数十分有效,由于其底层实现是hash表,因此可以在 O ( 1 ) \mathcal{O}(1) O(1)时间内进行查改,其实在这个意义上,数组也是可以的,但是数组的不足在于,对于某些极端数字,需要浪费大量内存,从这个意义上,hash表的优势便体现出来了,其实用map之类的映射都是可以的,但是map的底层实现不是hash表,在其存入,需要排序,而这个题并不需要排序,因此排序浪费的时间确实很浪费。
代码
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
vector<int> ans;
unordered_map<int, int> temp;//用于记录每个数字,和其在nums1中出现的次数
for(int i : nums1)
{
temp[i] += 1;
}
for(int i : nums2)
{
if(temp[i])
{
-- temp[i];//nums2中出现一次,相当于用掉了nums1中的一个该数字
ans.push_back(i);
}
}
return ans;
}
};
边栏推荐
猜你喜欢

How to use 120 lines of code to realize an interactive and complete drag and drop upload component?

The way to understand JS: the principle of object.call and object.create() inheritance

8 tips - database performance optimization, yyds~

Semaphore

Find the single dog (Li Kou 260)

实战演练 | 查找在给定时间范围内购买超过 N 件商品的客户

Tarjan 求强连通分量 O(n+m) ,缩点

Tid-mop: a comprehensive framework for security management and control under the scenario of data exchange

TID-MOP:面向数据交易所场景下的安全管控综合框架

8个小妙招调整数据库性能优化,yyds
随机推荐
Redis(八) - Redis企业实战之优惠券秒杀
计算物理期刊修改
What is Web3 game?
The way of understanding JS: write a perfect combination inheritance (Es5)
本地电脑架设传奇怎么开外网叫朋友一起玩?
Nodejs surface longitude
HNOI2012矿场搭建
Verilog语法基础HDL Bits训练 06
试除法--3的幂
Four characteristics and isolation level of MySQL transactions
Multitask programming
数据库工具对决:HeidiSQL 与 Navicat
YOLOV2 YOLO9000
一个List到底能存多大的数据呢?
SQL (basic 2)
C语言 预处理详解
In order to grasp the redis data structure, I drew 40 pictures (full version)
JVM 三色标记法与读写屏障
Find the single dog (Li Kou 260)
白蛋白纳米粒表面修饰低分子量鱼精蛋白LMWP/PEG-1900修饰牛血清白蛋白制备研究