当前位置:网站首页>一刷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
边栏推荐
- Advantages, disadvantages and selection of activation function
- Functions (Part I)
- [backtrader source code analysis 18] Yahoo Py code comments and analysis (boring, interested in the code, you can refer to)
- regular expression
- 基础贪心总结
- G007-hwy-cc-estor-03 Huawei Dorado V6 storage simulator construction
- Detailed explanation of kubernetes (IX) -- actual combat of creating pod with resource allocation list
- Modify the default listening IP of firebase emulators
- 网站建设与管理的基本概念
- Mumu, go all the way
猜你喜欢
How to design a good API interface?
携号转网最大赢家是中国电信,为何人们嫌弃中国移动和中国联通?
Detailed explanation of redirection and request forwarding
自主作业智慧农场创新论坛
Mysql database explanation (10)
What if the server is poisoned? How does the server prevent virus intrusion?
Explanation 2 of redis database (redis high availability, persistence and performance management)
Basic concepts of website construction and management
让阿里P8都为之着迷的分布式核心原理解析到底讲了啥?看完我惊了
Kubernetes详解(九)——资源配置清单创建Pod实战
随机推荐
网站建设与管理的基本概念
Openstack command operation
Baidu written test 2022.4.12 + programming topic: simple integer problem
什么是CNAS认证?CNAS认可的软件测评中心有哪些?
[leetcode daily question] install fence
Detailed explanation of kubernetes (XI) -- label and label selector
Go语言条件,循环,函数
Mumu, go all the way
Independent operation smart farm Innovation Forum
Pytorch中named_parameters、named_children、named_modules函数
kubernetes之常用Pod控制器的使用
Mobile finance (for personal use)
The wechat applet optimizes the native request through the promise of ES6
小程序知识点积累
Explanation of redis database (I)
How to design a good API interface?
Byte interview programming question: the minimum number of K
T2 iCloud日历无法同步
Hj31 word inversion
群体智能自主作业智慧农场项目启动及实施方案论证会议