Find the Duplicate number

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.