Leetcode287. Find the Duplicate Number

本文详细解析LeetCode第287题Find the Duplicate Number的两种解法:快慢指针法与二分查找法。通过将数组转换为链表的概念,使用快慢指针找到重复元素;并介绍了在限制条件下如何实现高效算法。

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

Leetcode287. Find the Duplicate Number

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Example 1:

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

Example 2:

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

Note:

  • You must not modify the array (assume the array is read only).
  • You must use only constant, O ( 1 ) O(1) O(1) extra space.
  • Your runtime complexity should be less than O ( n 2 ) O(n^2) O(n2)
  • There is only one duplicate number in the array, but it could be repeated more than once.
解法一:快慢指针

① 如果n个元素的数组中没有重复元素,且元素的取值范围为[1,n]。则把数组下标[0,n-1]放在集合a,元素的值[1,n]放在集合b,则集合a到集合b的映射一定是一对一的。

② 现在往数组里任意加了一个元素取值在[1,n],则集合a到集合b的映射不是一对一的,一定有两个下标指向同一个元素。

  • 数组中有一个重复的整数 <=> 链表中存在环
  • 找到数组中的重复整数 <=> 找到链表的环入口

把这个数组看做是带环的链表,要找的重复元素就是环的入口,即Leetcode142. Linked List Cycle II,所以这题的关键就是要理解如何将输入的数组看作为链表。

  1. 假设数组中没有重复元素,如[1,3,4,2],把下标与值的对应关系 index->number 写出来①0–>1 ②1–>3 ③2–>4 ④3–>2。我们可以得到一个链表:0->1->3->2->4->null,即①->②->④->③->null。这样我们就把数组转换成了链表。

    注:上述只是为了帮助理解数组转换为链表的情况,实际上这个转换有可能被终止,比如[1,5,3,2,4],把下标与值的对应关系写出来①0–>1 ②1–>5 ③2–>3 ④3–>2 ⑤4–>4,这样在①->②的时候就已经终止了。但是这种情况在数组中有重复元素的时候不会出现,因为数组元素个数为n+1个,元素值为[1,n],不会发生数组越界的情况。

  2. 假设数组中有重复元素,如[1,5,3,2,3,4],同理写出对应关系①0–>1 ②1–>5 ③2–>3 ④3–>2 ⑤4–>3 ⑥5–>4。可以得到另一个链表:0->1->5->4->3->2->3->2…,即 ①->②->⑥->⑤->④ <-> ③,链表在③④这里成环了,

    上面还有一种特殊情况,即元素的index=number,如[1,5,3,2,4,3],循环是0->1->5->3->2->3->2,并不会索引到4,但不会影响到结果

根据上述数组转链表的映射关系,可推出
1慢指针走一步slow = slow.next => slow = nums[slow]
1快指针走两步fast = fast.next.next => fast = nums[nums[fast]]

public class Solution {
    public int findDuplicate(int[] nums) {
        int fast = nums[0], slow = nums[0];
        while (true) {
            fast = nums[nums[fast]];
            slow = nums[slow];
            if (fast == slow) break;
        }
        fast = nums[0];
        while (slow != fast) {
            slow = nums[slow];
            fast = nums[fast];
        }
        return fast;
    }
}
解法二 二分查找

想不来

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值