class Solution {
public int findDuplicate(int[] nums) {
int slow = 0;
int fast = 0;
slow = nums[slow];
fast = nums[nums[fast]];
while(slow != fast){
slow = nums[slow];
fast = nums[nums[fast]];
}
int pre1 = 0;
int pre2 = slow;
while(pre1 != pre2){
pre1 = nums[pre1];
pre2 = nums[pre2];
}
return pre1;
}
}
使用二分查找
func findDuplicate(nums []int) int {
lo, hi := 1, len(nums)-1
for lo < hi {
mid := (lo + hi) >> 1
count := 0
for i := 0; i < len(nums); i++ {
if nums[i] <= mid {
count++
}
}
if count > mid {
hi = mid
} else {
lo = mid + 1
}
}
return lo
}