题目地址:
https://www.lintcode.com/problem/find-the-duplicate-number/description
给定一个数组,长度为 N + 1 N+1 N+1,数组中的数字范围是 [ 1 , N ] [1,N] [1,N]的整数,有且仅有一个数字出现了多于 1 1 1次,要求将其求出。
思路是链表求环。参考https://blog.csdn.net/qq_46105170/article/details/104018748。代码如下:
public class Solution {
/**
* @param nums: an array containing n + 1 integers which is between 1 and n
* @return: the duplicate one
*/
public int findDuplicate(int[] nums) {
// write your code here
int slow, fast;
slow = fast = 0;
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow != fast);
// 接下来用链表求环的入口的办法求重复数字。
int p = 0;
while (p != slow) {
p = nums[p];
slow = nums[slow];
}
return p;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。