当前位置:网站首页>《剑指offer 03》数组中重复的数字
《剑指offer 03》数组中重复的数字
2022-07-03 11:02:00 【爱敲代码的小邢~】
《剑指offer 03》数组中重复的数字
【leetcode链接】
【题目】
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 1:
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:
2 或 3
【思路】
仔细复习题目得知,nums中的所有数都在0~n-1中,所以数组中的每个数都会有一个与其值相等的下标与之对应,如下图所示:

所以我们可以通过依次匹配相应元素与下表并判断当前元素与当前元素值对应下标元素值是否相同来判断是否元素重复。
具体步骤如下:

这里要注意的是,当我们交换了元素之后,还需要检查当前元素是否与当前下标匹配,因为这步交换操作只能保证交换过去的元素与之下标对应,并不能保证交换过来的元素与这边的下标对应。而只有前面元素和下标对应了,在后面才有可能找到重复的元素。
最后,如果遍历完数组还没有找到重复的元素代表没有重复的元素。
【代码实现】
class Solution {
public:
int findRepeatNumber(vector<int>& nums) {
for(int i=0;i<nums.size();i++)
{
while(i!=nums[i])
{
if(nums[i]==nums[nums[i]])
return nums[i];
swap(nums[i],nums[nums[i]]);
}
}
return -1;
}
};
【时间复杂度&空间复杂度】
对于时间复杂度,虽然代码中一个for循环套着一个while循环,但是while循环的次数是常数次,所以时间复杂度为O(N)
于时间复杂度,虽然代码中一个for循环套着一个while循环,但是while循环的次数是常数次,所以时间复杂度为O(N)
因为我们在代码中没有使用额外的空间,故空间复杂度为O(1)。
边栏推荐
- 用了这么久线程池,你真的知道如何合理配置线程数吗?
- Excel表格转到Word中,表格不超边缘纸张范围
- 外插散点数据
- 同事写了一个责任链模式,bug无数...
- STL教程8-map
- R语言使用gridExtra包的grid.arrange函数将lattice包的多个可视化图像横向组合起来,ncol参数自定义组合图列数、nrow参数自定义组合图行数
- 鸿蒙第四次培训
- Capturing and sorting out external Fiddler -- Conversation bar and filter [2]
- 如何将数字字符串转换为整数
- Use typora to draw flow chart, sequence diagram, sequence diagram, Gantt chart, etc. for detailed explanation
猜你喜欢

Qt+VTK+OCCT读取IGES/STEP模型

Processes and threads

Machine learning 3.2 decision tree model learning notes (to be supplemented)
![抓包整理外篇fiddler———— 会话栏与过滤器[二]](/img/04/e9cc027d753e7049f273d866eefdce.png)
抓包整理外篇fiddler———— 会话栏与过滤器[二]

STL教程10-容器共性和使用场景

Excel quick cross table copy and paste

Incremental database backup - DB incr DB full

How should intermediate software designers prepare for the soft test

uniapp scroll view 解决高度自适应、弹框滚动穿透等问题。

DS90UB949
随机推荐
GCC compilation process and dynamic link library and static link library
ASP.NET-酒店管理系统
Web安全总结
一些常用术语
鸿蒙第四次培训
How PHP solves the problem of high concurrency
Spl06-007 air pressure sensor (example of barometer)
Extrapolated scatter data
解决msvcp120d.dll和msvcr120d.dll缺失
uniapp scroll view 解决高度自适应、弹框滚动穿透等问题。
Leetcode 46: full arrangement
C language two-dimensional array
How to clean up v$rman_ backup_ job_ Details view reports error ora-02030
2022年中南大学夏令营面试经验
Use typora to draw flow chart, sequence diagram, sequence diagram, Gantt chart, etc. for detailed explanation
POI excel cell wrap
Mmc5603nj geomagnetic sensor (Compass example)
After setting up ADG, instance 2 cannot start ora-29760: instance_ number parameter not specified
R language uses data The table package performs data aggregation statistics, calculates window statistics, calculates the median of sliding groups, and merges the generated statistical data into the o
After a month, I finally got Kingdee offer! Share tetrahedral Sutra + review materials