[LeetCode]Find the Duplicate Number 寻找数组重复值

Find the Duplicate Number 寻找数组重复值

题意:给定一个包含n+1个整数的数组,其中每个整数在1到n之间,只存在一个重复值,寻找数组中的重复值,保证空间复杂度为O(1),而且时间复杂度不能为O(n^2)。

二分搜索

思路:n个槽需要放置n+1个数字,那么必然会出现一个槽存在两个数字,这就是鸽巢原理,所以如果在给定的槽(下标)中,存在个数大于槽的情况则说明该区间存在重复值。

class Solution(object):
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return None
        left, right = 1, len(nums)
        while left < right:
            mid = (left + right) // 2
            cnt = 0
            for n in nums:
                if n <= mid:
                    cnt += 1
            if cnt <= mid:
                left = mid + 1
            else:
                right = mid
        return left
posted @ 2017-09-15 02:27  banananana  阅读(202)  评论(0)    收藏  举报