LeetCode-Find the Duplicate Number
Description:
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:
- 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.
题意:找出数组中重复出现得元素;并且时间复杂度不超过O(n2),空间复杂度为O(1);
解法:这里用到了Floyd判圈算法(龟兔赛跑算法);第一步找出数组中存在的环(数组元素代表的就是下一个元素的位置,因为这里元素的大小在[1,n]),第二步找到环的入口,如图所示:
Java
class Solution {
public int findDuplicate(int[] nums) {
int tortoise = nums[0];
int hare = nums[0];
do {
tortoise = nums[tortoise];
hare = nums[nums[hare]];
} while (tortoise != hare);
int ptr = nums[0];
while (ptr != tortoise) {
ptr = nums[ptr];
tortoise = nums[tortoise];
}
return ptr;
}
}
参考文献:
[1]:https://blog.****.net/xyzxiaoxiong/article/details/78761940
[2]:https://en.wikipedia.org/wiki/Cycle_detection#Floyd’s_Tortoise_and_Hare