当前位置:网站首页>哈希表应用:只出现一次的数字
哈希表应用:只出现一次的数字
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]
边栏推荐
- A Sina Weibo semantic sentiment analysis tool developed by ABAP
- MySQL 原理与优化:Update 优化
- SWIG Tutorial "One"
- 匿名函数和全部内置函数详细认识(下篇)
- 网络工程师的背包(EDC总结推荐)
- Cesium Quick Start 4-Polylines primitive usage explanation
- Introduction to the Internet (2)
- “蔚来杯“2022牛客暑期多校训练营7
- Chapter one module of the re module,
- 【教程】HuggingFace的Optimum组件已支持加速Graphcore和英特尔Habana芯片
猜你喜欢

消息称原美图高管加盟蔚来手机 顶配产品或超7000元

fatal error C1083 Unable to open include file 'io.h' No such file

Cesium Quick Start 4-Polylines primitive usage explanation

It is reported that the original Meitu executive joined Weilai mobile phone, the top product may exceed 7,000 yuan

Recommend a few had better use the MySQL open source client, collection!

秒杀项目收获

一个 ABAP 工具,能打印系统里某个用户对 BSP 应用的浏览历史记录

Redis -- Nosql

Oracle database backup DMP file is too big, what method can be split into multiple DMP when backup?

Introduction to the functional logic of metaForce Fosage 2.0 system development
随机推荐
QOS功能介绍
为什么中国的数字是四位一进,而西方的是三位一进?
Boss raises salary!Look at my WPF Loading!!!
redis 源码源文件说明
TCP为什么是三次握手和四次挥手?
web安全入门-Kill Chain测试流程
兆骑科创高层次人才创业大赛平台,投融资对接,双创服务
【服务器数据恢复】raid5崩溃导致lvm信息和VXFS文件系统损坏的数据恢复案例
Introduction to the functional logic of metaForce Fosage 2.0 system development
Network engineer's backpack (EDC summary recommendation)
scala 10种函数高级应用
[Letter from Wu Enda] The development of reinforcement learning!
[Semantic Segmentation] DeepLab Series
FP6378AS5CTR SOT-23-5 高效1MHz2A同步降压调节器
并发容器线程安全应对之道
腾讯云TDP-对象存储COS产品新用户福利
Redis -- Nosql
Redis -- Nosql
Meaning and names of 12 nautical miles, 24 nautical miles and 200 nautical miles
小程序-语音播报功能