当前位置:网站首页>哈希表应用:只出现一次的数字
哈希表应用:只出现一次的数字
2022-08-10 15:20:00 【^o^叶子^0^】
目录
题目描述
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
说明:
你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?
示例 1:
输入: [2,2,1]
输出: 1
示例 2:
输入: [4,1,2,1,2]
输出: 4
AC代码
class Solution {
public:
int singleNumber(vector<int>& nums) {
unordered_map<int,int>hashmap;
for(auto & it:nums)++hashmap[it];
for(auto & [key,value]:hashmap)if(value==1)return key;
return 0;
}
};
解析
很像python的字典。
unordered_map的内部实现了一个哈希表,有键和值对应,键不会重复,就像字典一样,页数与内容,用来解决这道题实在是太方便了,用切片提取vector的元素,把它作为哈希表的键,出现次数作为对应的值,哈希表还会自己新增进去,都不需要判断有没有,自己就会做判断,装完哈希表之后遍历一下找出出现次数为1的就可以了。
话说C++的切片,还能提取多个元素,我到目前为止,只知道在C++中,字符串、set、vector,以及今天学的unordered_map可以切片,不过,话说回来,哈希表是真的巨好用@[email protected]
边栏推荐
- Chapter II Module Encyclopedia "collections Module"
- websocket实现实时变化图表内容
- Scala collections
- Mysql statement analysis, storage engine, index optimization, etc.
- 消息称原美图高管加盟蔚来手机 顶配产品或超7000元
- 程序调试介绍及其使用
- Appium for APP automation testing
- QOS function introduction
- Go Context基本使用
- Oracle数据库备份dmp文件太大,有什么办法可以在备份的时候拆分成多个dmp吗?
猜你喜欢
电商秒杀项目收获(二)
fastposter v2.9.1 程序员必备海报生成器
一个 ABAP 工具,能打印系统里某个用户对 BSP 应用的浏览历史记录
FP6378AS5CTR SOT - 23-5 effective 1 mhz2a synchronous buck regulator
2025年推出 奥迪透露将推出大型SUV产品
JS 从零手写实现一个bind方法
【服务器数据恢复】raid5崩溃导致lvm信息和VXFS文件系统损坏的数据恢复案例
Oracle database backup DMP file is too big, what method can be split into multiple DMP when backup?
JVM学习——2——内存加载过程(类加载器)
Rich Dad Poor Dad Reading Notes
随机推荐
JS entry to proficient full version
pytest框架优化
Chapter II Module Encyclopedia "collections Module"
HUAWEI CLOUD DevCloud received the highest-level certification of the first batch of cloud-native technology architecture maturity assessments by the China Academy of Information and Communications Te
易观千帆银行用户体验中心:聚焦银行APP用户体验
12海里、24海里、200海里的意义及名称
Detailed understanding of anonymous functions and all built-in functions (Part 2)
[Data warehouse design] Why should enterprise data warehouses be layered?(six benefits)
Yi Gene|In-depth review: epigenetic regulation of m6A RNA methylation in brain development and disease
易基因|深度综述:m6A RNA甲基化在大脑发育和疾病中的表观转录调控作用
A test tool for ABAP Development Tool custom service endpoint
Systemui status bar to add a new icon
Yann LeCun转推:参数减少50倍,性能还更好,MetaAI推出Atlas信息检索模型
十年架构五年生活-09 五年之约如期而至
XML基本学习
JVM学习——2——内存加载过程(类加载器)
Websocket realizes real-time change of chart content
Mobileye携手极氪通过OTA升级开启高级驾驶辅助新篇章
产品说明丨如何使用MobPush快速创建应用
异地多活方法论