[Leetcode] Find the Duplicate Number, Solution
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Note:
- You must not modify the array (assume the array is read only).
- You must use only constant, O(1) extra space.
- Your runtime complexity should be less than
O(n2)
. - There is only one duplicate number in the array, but it could be repeated more than once.
[Thoughts]
这题想清楚了就不难,想不清楚就麻烦。
假设数组A长度是n, 里面存储1到n的整数,那么很清楚,我们可以在按照A[i] = i+1,进行排序。但是现在有n+1个整数,而且至少有一个数字存在冗余。如果我们仍然按照A[i] = i+1来排序数组的话,那么当发现A[i]上已经是i+1的值时,说明我们已经找到了冗余数了。
举个例子,
简单的说,就是遍历数组的同时,按照A[i]应该放到A[A[i]]原则,进行swap,第一个无法swap的数字就是所求。
[Code]
1: class Solution {
2: public:
3: int findDuplicate(vector<int>& nums) {
4: int length = nums.size();
5: for(int i =0; i< length; i++) {
6: if(nums[i] == i+1) {
7: continue;
8: }
9: int oldIndex = i;
10: int newIndex = nums[i]-1;
11: while(nums[oldIndex] != oldIndex +1 ) {
12: if(nums[oldIndex] == nums[newIndex] ) {
13: return nums[oldIndex];
14: }
15: int temp = nums[newIndex];
16: nums[newIndex] = nums[oldIndex];
17: nums[oldIndex] = temp;
18: newIndex = nums[oldIndex] -1;
19: }
20: }
21: }
22: };
github: https://github.com/codingtmd/leetcode/blob/master/src/Find_the_Duplicate_Number.cpp
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· C# 13 中的新增功能实操
· Supergateway:MCP服务器的远程调试与集成工具