给出一个数组 nums 包含 n + 1 个整数,每个整数是从 1 到 n (包括边界),保证至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
注意事项:
- 不能修改数组(假设数组只能读)
- 只能用额外的O(1)的空间
- 时间复杂度小于O(n^2)
- 数组中只有一个重复的数,但可能重复超过一次
样例:
给出 nums = [5,5,4,3,2,1],返回 5.
给出 nums = [5,4,4,3,2,1],返回 4.
思路:
由于数组大小n+1,元素的取值范围1~n,可以建立下标到数组元素的映射,同时数组元素也可以作为下标,例如{1,2,3,1},映射关系为{0,3}->1,1->2,2->3,会形成环。
参考 单链表判断是否有环且求环入口
可以求出映射中环的入口,也就是重复数字。
#ifndef C633_H
#define C633_H
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
/*
* @param nums: an array containing n + 1 integers which is between 1 and n
* @return: the duplicate one
*/
int findDuplicate(vector<int> &nums) {
// write your code here
int slow = 0;
int fast = 0;
do{
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
fast = 0;
while (fast != slow)
{
fast = nums[fast];
slow = nums[slow];
}
return fast;
}
};
#endif