当前位置:网站首页>《剑指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)。
边栏推荐
- R language uses grid of gridextra package The array function combines multiple visual images of the lattice package horizontally, and the ncol parameter defines the number of columns of the combined g
- STL教程9-容器元素深拷贝和浅拷贝问题
- Viewing binary bin files with notepad++ editor
- FL Studio 20 unlimited trial fruit arranger Download
- Gut | 香港中文大学于君组揭示吸烟改变肠道菌群并促进结直肠癌(不要吸烟)
- Numpy np. Max and np Maximum implements the relu function
- . \vmware-vdiskmanager. exe -k “c:\\xxxxx.vmdk”
- 软考中级软件设计师该怎么备考
- After watching the video, AI model learned to play my world: cutting trees, making boxes, making stone picks, everything is good
- Slam mapping and autonomous navigation simulation based on turnlebot3
猜你喜欢
随机推荐
MATLAB提取不規則txt文件中的數值數據(簡單且實用)
ftp登录时,报错“530 Login incorrect.Login failed”
外插散点数据
Slam mapping and autonomous navigation simulation based on turnlebot3
Double linked list of linear list
Multi dimensional monitoring: the data base of intelligent monitoring
Nestjs配置服务,配置Cookie和Session
(database authorization - redis) summary of unauthorized access vulnerabilities in redis
phpcms 提示信息页面跳转showmessage
Hongmeng third training (project training)
ASP.NET-酒店管理系统
C language utf8toutf16 (UTF-8 characters are converted to hexadecimal encoding)
AI模型看看视频,就学会了玩《我的世界》:砍树、造箱子、制作石镐样样不差...
ORACLE进阶(一) 通过EXPDP IMPDP命令实现导dmp
[OBS] configFile in ini format of OBS
Qt+VTK+OCCT读取IGES/STEP模型
金额计算用 BigDecimal 就万无一失了?看看这五个坑吧~~
软件测试周刊(第78期):你对未来越有信心,你对现在越有耐心。
Nestjs configuration service, configuring cookies and sessions
P3250 [HNOI2016] 网络 + [NECPC2022] F.Tree Path 树剖+线段树维护堆








