Topic:
Given an array nums containing n + 1 integers where each integer is between 1 and N (inclusive), prove that at least O NE duplicate number must exist. Assume that there are 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 is less than O (N2). There is a duplicate number in the array, but it could was repeated more than once.
Analysis: Because the repeating number must be between 1-n, we use the binary lookup method, Initialize left = 1, right = N, not to assume that the repeating number is Mid = (left + right)/2. Then iterate through the array, calculating the number of elements less than or equal to mid, num, if num > mid , you only need to find the number of duplicates between left and mid-1, otherwise look for duplicates between mid+1 and right. The integer left is the number of duplicates to look for when the loop condition is not met by <= right.
The Java code is as follows:
Public intFindduplicate (int[] nums) { intleft = 1; intright = Nums.length-1; while(Left <=Right ) { intMid = (left + right)/2; intnum =Countnum (Nums, mid); if(Num >mid) { Right= Mid-1; } Else{ Left= Mid + 1; } } returnLeft ; } Public intCountnum (int[] Nums,inttarget) { intSum =0; for(inti = 0; i < nums.length; i++) { if(Nums[i] <=target) {Sum++; } } returnsum; }
Find the Duplicate number