題目地址:
https://www.lintcode.com/problem/find-the-duplicate-number/description
給定一個數組,長度爲,數組中的數字範圍是的整數,有且僅有一個數字出現了多於次,要求將其求出。
思路是鏈表求環。參考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;
}
}
時間複雜度,空間。