leetcode 287. Find the Duplicate Number #Hard
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.
题意:长度为n+1的数组中每个元素都在[1,n]之间,证明数组中出有重复元素(假设数组中只有一个重复元素,找到这个重复元素)
要求:不可修改数组,O(1)的空间复杂度,低于O(n^2)的时间复杂度
映射找环法:具体分析略复杂,见地址
int findDuplicate(int* nums, int numsSize) {
int r,slow,fast;
for(slow=nums[0],fast=nums[nums[0]];slow!=fast;slow=nums[slow],fast=nums[nums[fast]]);
for(r=0;r!=slow;slow=nums[slow],r=nums[r]);
return r;
}