当前位置:网站首页>《剑指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)。
边栏推荐
- How to mix embedded MCU, arm and DSP?
- PHP server interacts with redis with a large number of close_ Wait analysis
- C language log base zlog basic use
- 用了这么久线程池,你真的知道如何合理配置线程数吗?
- Understand go language context in one article
- 抓包整理外篇fiddler———— 会话栏与过滤器[二]
- C language AES encryption and decryption
- 同事写了一个责任链模式,bug无数...
- Capturing and sorting out external Fiddler -- Conversation bar and filter [2]
- ASP. Net hotel management system
猜你喜欢
Viewing binary bin files with notepad++ editor
银泰百货点燃城市“夜经济”
Xml的(DTD,xml解析,xml建模)
(数据库提权——Redis)Redis未授权访问漏洞总结
Machine learning 3.2 decision tree model learning notes (to be supplemented)
FL Studio 20无限试用版水果编曲下载
ASP.NET-酒店管理系统
MATLAB提取不規則txt文件中的數值數據(簡單且實用)
Kubernetes 三打探针及探针方式
How to get started embedded future development direction of embedded
随机推荐
用了这么久线程池,你真的知道如何合理配置线程数吗?
一些常用术语
POI excel cell wrap
uniapp实现点击加载更多
Leetcode 46: full arrangement
Programmers' entrepreneurial trap: taking private jobs
Slam mapping and autonomous navigation simulation based on turnlebot3
2022年湖南工学院ACM集训第二次周测题解
Excel快速跨表复制粘贴
R language uses the aggregate function to calculate the mean value (sum) of dataframe data grouping aggregation without setting na The result of RM calculation. If the group contains the missing value
.\vmware-vdiskmanager.exe -k “c:\\xxxxx.vmdk”
一文搞懂Go语言Context
How PHP solves the problem of high concurrency
Matlab extracts numerical data from irregular txt files (simple and practical)
2022 northeast four provinces match VP record / supplementary questions
asyncio 警告 DeprecationWarning: There is no current event loop
Hongmeng third training (project training)
Oracle withdraw permission & create role
AOSP ~ NTP ( 网络时间协议 )
How to make others fear you