博客
关于我
leetcode刷题42——数组的交集系列
阅读量:727 次
发布时间:2019-03-21

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

给定两个数组,编写一个函数来计算它们的交集。输出结果中的每个元素一定是唯一的,可以不考虑输出结果的顺序。

方法一:使用排序和集合

这种方法通过对两个数组进行排序,然后使用标准库中的set_intersection函数找出交集元素。最后,使用unique函数去除重复元素:

#include 
#include
#include
using namespace std;vector
intersection(vector
& nums1, vector
& nums2) { vector
v; sort(nums1.begin(), nums1.end()); sort(nums2.begin(), nums2.end()); set_intersection(nums1.begin(), nums1.end(), nums2.begin(), nums2.end(), back_inserter(v)); auto it = unique(v.begin(), v.end()); if (it != v.end()) { v.erase(it, v.end()); } return v;}

方法二:使用哈希表

这种方法通过先将数组元素映射到哈希表中,然后检查元素是否存在于两个哈希表中,从而记录交集元素:

#include 
#include
using namespace std;vector
intersection(vector
& nums1, vector
& nums2) { unordered_set
hash1; unordered_set
hash2; vector
v; for (int num : nums1) { hash1.insert(num); } for (int num : nums2) { if (hash1.count(num) && !hash2.count(num)) { v.push_back(num); } hash2.insert(num); } return v;}

方法三:处理频率最低的元素

这种方法通过统计每个元素的频率,取两个数组中最小频率的元素:

#include 
#include
using namespace std;vector
intersect(const vector
& nums1, const vector
& nums2) { unordered_map
counter; for (int num : nums1) { counter[num]++; } vector
result; for (int num : nums2) { if (counter[num] > 0) { result.push_back(num); counter[num]--; } } return result;}

选择方法

选择哪一种方法取决于具体需求。第一种方法简单且有效,但在处理大数据量时可能较慢。第二种方法通过哈希表提高了效率,第三种方法则处理了元素频率的问题。

按照题目要求,每个元素在结果中只出现一次,因此无论选择哪种方法,只要确保交集元素唯一即可。如果需要优化性能,第二种方法通常更好。

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

你可能感兴趣的文章
Python合并两张图片 | 先叠透明度再合并 (附Demo)
查看>>
python各进制的表述与转换
查看>>
python各种库安装
查看>>
python可视化matplotlib_如何使用Python中最强大的可视化工具Matplotlib?
查看>>
python可维护性_使用这7大神器,让你的Python 代码更容易于维护
查看>>
python变量的详细教程_Python零基础入门教程之语法入门[变量](第二期)
查看>>
Python变量命名方法-ChatGPT4o作答
查看>>
Python变量与运算符
查看>>
python单元测试之unittest
查看>>
Python单元测试unittest实战
查看>>
python协程实时输出_Python 协程以及事件循环的问题,怎么知道 IO 读取结束了呢?...
查看>>
Python化身“安全老中医”:一键搞定工控系统漏洞,从零基础到精通,收藏这篇就够了!
查看>>
Python加速运行技巧
查看>>
python办公自动化基础遍历文件夹
查看>>
python办公自动化基础输出文件和文件夹
查看>>
python办公自动化基础搜索文件
查看>>
python前端之css
查看>>
Python制作进度条,原来有这么多方法
查看>>
Python制作简单的学生成绩管理系统
查看>>
python制作甘特图的基本知识(附Demo)
查看>>