美文网首页
25 - Hard - 寻找重复数

25 - Hard - 寻找重复数

作者: 1f872d1e3817 | 来源:发表于2018-05-17 11:51 被阅读0次

给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间,包括 1 和 n ,可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。

示例 1:

输入: [1,3,4,2,2]
输出: 2
示例 2:

输入: [3,1,3,4,2]
输出: 3
说明:

不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n2) 。
数组中只有一个重复的数字,但它可能不止重复出现一次。

二分搜索法,我们在区别[1, n]中搜索,首先求出中点mid,然后遍历整个数组,统计所有小于等于mid的数的个数,如果个数大于mid,则说明重复值在[mid+1, n]之间,反之,重复值应在[1, mid-1]之间,然后依次类推,直到搜索完成,此时的low就是我们要求的重复值

class Solution:
    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        low, high = 1, len(nums)-1
        while low < high:
            mid = low + (high-low)//2
            count = 0
            for i in nums:
                if i <= mid:
                    count += 1
            if count <= mid:
                low = mid + 1
            else:
                high = mid
        return low

快慢指针法!由于题目限定了区间[1,n],所以可以巧妙的利用坐标和数值之间相互转换,而由于重复数字的存在,那么一定会形成环,我们用快慢指针可以找到环并确定环的起始位置。
时O(?), 空O(1)

    def findDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        slow, fast, t = 0, 0, 0
        while True:
            print(slow, nums[slow])
            slow = nums[slow]
            print(fast, nums[fast], nums[nums[fast]])
            fast = nums[nums[fast]]
            print()
            if slow == fast:
                break
        while True:
            slow = nums[slow]
            t = nums[t]
            if slow == t:
                break
        return slow

相关文章

网友评论

      本文标题:25 - Hard - 寻找重复数

      本文链接:https://www.haomeiwen.com/subject/pmhbdftx.html