解题思路:二分法。在区间[1, n]中搜索,首先求出中点mid,然后遍历整个数组,统计所有小于等于mid的数的个
数,如果个数小于等于mid,则说明重复值在[mid+1, n]之间,反之,重复值应在[1, mid-1]之间,然后依次类推,
直到搜索完成,此时的right就是我们要求的重复值。
public int findDuplicate(int[] nums)
{
int low = 0;
int high = nums.length-1;
int mid = 0, count = 0;
while (low < high)
{
mid = (low + high) / 2;
count = 0;
for (int num: nums)
{
if (num <= mid)
count++;
}
if (count <= mid)
low = mid + 1;
else
high = mid;
}
return low;
}