LeetCode //C - 287. Find the Duplicate Number

287. Find the Duplicate Number

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

Example 3:

Input: nums = [3,3,3,3,3]
Output: 3

Constraints:
  • 1 < = n < = 1 0 5 1 <= n <= 10^5 1<=n<=105
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.

From: LeetCode
Link: 287. Find the Duplicate Number


Solution:

Ideas:
  1. Initialization: Both the tortoise and the hare start at the first element (index 0).

  2. Phase 1 - Detecting the cycle:

  • The tortoise moves one step at a time (nums[tortoise]), while the hare moves two steps at a time (nums[nums[hare]]).
  • If there’s a cycle (which there is, due to the duplicate), the hare will eventually meet the tortoise within this cycle, proving the cycle’s existence.
  1. Phase 2 - Locating the cycle’s start:
  • After the meeting, reset one of the runners to the start of the list (index 0), keeping the other at the meeting point.
  • Move both at the same speed (one step at a time). The point at which they meet again is the start of the cycle, which corresponds to the duplicate number in the array.
Code:
int findDuplicate(int* nums, int numsSize) {
    // Phase 1: Finding the intersection point of the two runners.
    int tortoise = nums[0];
    int hare = nums[0];
    do {
        tortoise = nums[tortoise];
        hare = nums[nums[hare]];
    } while (tortoise != hare);

    // Phase 2: Find the "entrance" to the cycle.
    tortoise = nums[0];
    while (tortoise != hare) {
        tortoise = nums[tortoise];
        hare = nums[hare];
    }

    return hare;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Navigator_Z

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

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

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

打赏作者

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

抵扣说明:

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

余额充值