Binary9

题目描述[原题链接][https://leetcode-cn.com/problems/find-the-duplicate-number/]

给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。

示例 1:

输入: [1,3,4,2,2]
输出: 2

示例 2:

输入: [3,1,3,4,2]
输出: 3

说明:

不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n^2)
数组中只有一个重复的数字,但它可能不止重复出现一次。

算法描述

​ 使用的算法是:弗洛伊德的乌龟和兔子(循环检测),首先,我们可以很容易地证明问题的约束意味着必须存在一个循环。因为 nums 中的每个数字都在 1 和 n 之间,所以它必须指向存在的索引。此外,由于 0不能作为 nums 中的值出现,nums[0] 不能作为循环的一部分。

C++代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int tortoise = nums[0];
int here = nums[0];
do{
tortoise = nums[tortoise];
here = nums[nums[here]];
}while(tortoise!=here);

int ptr1=nums[0];
int ptr2=tortoise;
while(ptr1!=ptr2){
ptr1=nums[ptr1];
ptr2 = nums[ptr2];
}
return ptr1;
}
};

Java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int findDuplicate(int[] nums) {
int tortoise = nums[0];
int here = nums[0];
do{
tortoise = nums[tortoise];
here = nums[nums[here]];
}while(tortoise!=here);
int ptr1=nums[0];
int ptr2 = tortoise;
while(ptr1!=ptr2){
ptr1 = nums[ptr1];
ptr2 = nums[ptr2];
}
return ptr1;
}
}