Find the Duplicate Number

文章介绍了一种解决给定数组中唯一重复整数问题的方法,利用FloydsTortoiseandHare算法,通过两个指针(慢指针和快指针)在不修改数组且只使用常量额外空间的情况下找到重复数。算法的时间复杂度为O(n),空间复杂度为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one repeated number in nums, return this repeated number.

You must solve the problem without modifying the array nums and uses only constant extra space.

Example 1:

Input: nums = [1,3,4,2,2]
Output: 2

Example 2:

Input: nums = [3,1,3,4,2]
Output: 3

Intuition

This problem involves finding a cycle in an array where each element in the array represents the next index to jump to. The Floyd's Tortoise and Hare algorithm can be applied to detect a cycle in this context.

Approach

Use two pointers, slow and fast, initialized to the first element of the array.
Move slow one step at a time and fast two steps at a time.
If there is a cycle, the two pointers will eventually meet.
After detecting the cycle, reset one of the pointers (let's say slow) to the beginning.
Move both pointers one step at a time until they meet again. The meeting point is the start of the cycle.
The value at the meeting point is the repeated number.

Complexity

  • Time complexity:

The time complexity is O(n), where n is the length of the array. The algorithm makes two passes over the array: the first to detect the cycle and the second to find the start of the cycle.

  • Space complexity:

The space complexity is O(1) as the algorithm uses only constant extra space.

Code

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        slow , fast = 0 , 0
        while True:
            slow = nums[slow]
            fast = nums[nums[fast]]
            if slow == fast:
                break

        slow2 = 0
        while True:
            slow = nums[slow]
            slow2 = nums[slow2]
            if slow == slow2:
                return slow
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值