当前位置:网站首页>一刷312-简单重复set-剑指 Offer 03. 数组中重复的数字(e)
一刷312-简单重复set-剑指 Offer 03. 数组中重复的数字(e)
2022-04-23 15:35:00 【丿唐宋】
题目:
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,
但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
---------------------------
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
限制:
2 <= n <= 100000
-------------------
思路: 遍历数组
由于只需要找出数组中任意一个重复的数字,因此遍历数组,遇到重复的数字即返回。
为了判断一个数字是否重复遇到,使用集合存储已经遇到的数字,如果遇到的一个数字已经在集合中,
则当前的数字是重复数字。
初始化集合为空集合,重复的数字 repeat = -1
遍历数组中的每个元素:
将该元素加入集合中,判断是否添加成功
如果添加失败,说明该元素已经在集合中,因此该元素是重复元素,将该元素的值赋给 repeat,并结束遍历
返回 repeat
------------------
复杂性分析
时间复杂度:O(n)
遍历数组一遍。使用哈希集合(HashSet),添加元素的时间复杂度为 O(1),故总的时间复杂度是 O(n)
空间复杂度:O(n)。不重复的每个元素都可能存入集合,因此占用 O(n) 额外空间。
--------------------
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (set.contains(num)) return num;
set.add(num);
}
return -1;
}
}
涉及到简单重复问题: set
版权声明
本文为[丿唐宋]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_45170946/article/details/124359079
边栏推荐
- Rsync + inotify remote synchronization
- Collation of errors encountered in the use of redis shake
- fatal error: torch/extension. h: No such file or directory
- 机器学习——逻辑回归
- Squid agent
- Krpano panorama vtour folder and tour
- 移动金融(自用)
- utils.DeprecatedIn35 因升级可能取消,该如何办
- 今日睡眠质量记录76分
- Sorting and replying to questions related to transformer
猜你喜欢

Detailed explanation of kubernetes (IX) -- actual combat of creating pod with resource allocation list

How to design a good API interface?

regular expression

Sword finger offer (2) -- for Huawei

让阿里P8都为之着迷的分布式核心原理解析到底讲了啥?看完我惊了

Wechat applet customer service access to send and receive messages
![[leetcode daily question] install fence](/img/4e/3ac23174f2b3ee867b45a2e748b872.png)
[leetcode daily question] install fence

Special analysis of China's digital technology in 2022

自主作业智慧农场创新论坛

Basic concepts of website construction and management
随机推荐
【递归之数的拆分】n分k,限定范围的拆分
山寨版归并【上】
深度学习——超参数设置
CVPR 2022 优质论文分享
Detailed explanation of MySQL connection query
考试考试自用
Cookie&Session
Node. JS ODBC connection PostgreSQL
开源项目推荐:3D点云处理软件ParaView,基于Qt和VTK
Analysis of common storage types and FTP active and passive modes
Summary of interfaces for JDBC and servlet to write CRUD
Sword finger offer (1) -- for Huawei
删除字符串中出现次数最少的字符
Use of common pod controller of kubernetes
Rsync + inotify remote synchronization
Differential privacy (background)
Hj31 word inversion
Example of time complexity calculation
服务器中毒了怎么办?服务器怎么防止病毒入侵?
Multitimer V2 reconstruction version | an infinitely scalable software timer