您的位置:首页 > 其它

Find the Duplicate Number

2015-10-28 17:56 316 查看
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.

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.

思路: 给定n+1个整数,其范围都在1~n之间,想象数轴上有个区间是[1,n],区间中间的数字为mid, 判断原n+1个数字,落在区间[1,mid]之间的数字总共有多少个,计为count;由于数字全部都是整数,那么[1,mid]这个区间最多能够容纳的不同整数为mid个,因为count个数字都是在[1,mid]之间的,如果说count比mid还要大,说明count个数字中肯定有重复的。这样就可以将区间折半,接下来的就在区间[1,mid]中去找重复的数字,同样的查找过程也可以将区间折半。。

实际上这n+1个数字在区间[1,n]上有整数落点,这个题目就是求在[1,n]之间哪个数字上落点是重复的,在上述将区间折半的过程中,最后一定是向那个重复落点的地方一步步逼近。

public class Solution {
public int findDuplicate(int[] nums) {
int n=nums.length;
if(n==0) return -1;
int left=1;
int right=nums.length-1;
while(left<=right)
{
int mid=left+(right-left)/2;
int count=0;
for(int i=0;i<nums.length;i++)
{
if(nums[i]<=mid)
count++;
}
if(count<=mid)
{
left=mid+1;
}
else right=mid-1;

}
return left;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: