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.

Example 1:

Input:

[1,3,4,2,2]

Output: 2

Example 2:

Input: [3,1,3,4,2]
Output: 3

Note:

  1. Youmust notmodify the array (assume the array is read only).
  2. You must use only constant,O(1) extra space.
  3. Your runtime complexity should be less thanO(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

题解:

自己的位运算写法超长度了。

class Solution {
public:
int findDuplicate(vector<int>& nums) {
int n = nums.size();
long long bit = 0;
for (int i = 0; i < n; i++) {
long long x = bit ^ ((long long)1 << nums[i]);
if (x < bit) {
return nums[i];
}
bit ^= (long long)1 << nums[i];
}
return 0;
}
};

看讨论区一个神级写法,把数组看成跳表,如果没有重复数那么跳表就是无环的,有重复数的话就是有环了,然后用链表中寻找环的快慢指针算法即可。

class Solution {
public:
int findDuplicate(vector<int>& nums) {
int n = nums.size();
if (n < 2) {
return -1;
}
int slow = nums[0], fast = nums[nums[0]];
while (slow != fast) {
slow = nums[slow];
fast = nums[nums[fast]];
}
int find = 0;
while (find != slow) {
find = nums[find];
slow = nums[slow];
}
return find;
}
};