287. 寻找重复数(Python)

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

示例 1:

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

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

方法一:常规想法
把元素装入一个temp数组,若temp已存在该元素,则返回该元素。

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        temp=[]
        for i in nums:
            if i not in temp:
                temp.append(i)
            else:
                return i

方法二:数学法
用原数组的和减去去重后的数组和,再除以少了的元素个数。

class Solution:
    def findDuplicate(self, nums: 'List[int]') -> int:
        m = len(nums)
        n = len(set(nums))
        sum1 = sum(nums)
        sum2 = sum(set(nums))
        result = (sum1 - sum2) // (m - n)
        return result

方法三:二分法
设数组长度为nn,则数组中元素∈[1,n−1],且只有一个重复元素。一个直观的想法,设一个数字k∈[1,n−1],统计数组中小于等于k的数字的个数count:
若count<=k,说明重复数字一定在(k,n−1]的范围内。
若count>k,说明重复数字一定在[0,k]的范围内。
利用这个性质,使用二分查找逐渐缩小重复数字所在的范围。

初试化左右 数字 边界left=1,right=n-1

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        left = 1
        right = len(nums) - 1
        while (left < right):
            mid = (left + right) // 2
            count = 0
            for num in nums:
                if (num <= mid):
                    count += 1
            if (count <= mid):
                left = mid + 1
            else:
                right = mid
        return left

方法三参考链接

### Python 实现 LeetCode 287 寻找组内的重复 对于在Python中解决寻找组内重复数字的问题,可以采用多种方法来处理这个问题。一种常见的高效解法是利用二分查找或者快慢指针的方法。 #### 方法一:二分查找 通过设定左右边界并逐步缩小范围直到找到重复元素的位置。这种方法不需要额外的空间开销,并且能够有效地减少时间复杂度。 ```python def findDuplicate(nums): low = 1 high = len(nums) - 1 while low <= high: mid = (low + high) >> 1 count = sum(num <= mid for num in nums) if count > mid: duplicate = mid high = mid - 1 else: low = mid + 1 return duplicate ``` 此段代码实现了基于二分查找的解决方案[^3]。 #### 方法二:快慢指针(Floyd 判圈算法) 该方法模仿链表检测环路的思想,在不改变输入组的情况下工作。它使用两个指针——一个移动速度快于另一个;当它们相遇时,则说明存在循环即找到了重复项。 ```python def findDuplicate(nums): tortoise = hare = nums[0] # Phase 1: Find the intersection point of two runners. while True: tortoise = nums[tortoise] hare = nums[nums[hare]] if tortoise == hare: break # Phase 2: Find the entrance to cycle (duplicate element). tortoise = nums[0] while tortoise != hare: tortoise = nums[tortoise] hare = nums[hare] return hare ``` 上述代码展示了如何应用 Floyd 的判圈算法来定位重复值。 这两种方式都能够在 O(n log n) 或者更优的时间复杂度下完成任务,并且不会修改原始据结构。如果考虑空间效率的话,建议优先尝试这些原地工作的算法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI小笔记

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值