Find the Duplicate Number

本文介绍了一种在不修改原数组且仅使用常数级额外空间的情况下,寻找数组中唯一重复数字的方法。通过二分查找思想逐步缩小搜索范围,最终确定重复的数字。

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;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值