leetcode287: Find the Duplicate Number

shuaishuai3409發表於2016-05-11

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,請證明至少存在一個重複的數字。假設只有一個重複的數,請找出這個數。

假設n=4,那麼陣列中應該有5個數,每個數的範圍為1~4且只有一個重複的數字。陣列在放完1 2 3 4 後,如果在放一個數字的話必然會產生重複,目的就是找出這個重複的數字。

要求:
不要更改陣列(限制你不要排序)
不要使用額外的空間(不要建立新的陣列)
時間複雜度小於O(n2

^2
)


思路:
利用二分的思想。初始化一個mid值,如果陣列中小於等於mid的值的個數小於等於mid這個值,那麼可以說明重複數字在mid的右面,反之說明重複數字在mid值的左面。

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

    }
}

相關文章