[算法分析与设计] leetcode 每周一题: Find the Duplicate Number

题目链接:https://leetcode.com/problems/find-the-duplicate-number/description/

题目:

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.

Note:

  1. You must not modify the array (assume the array is read only).
  2. You must use only constant, O(1) extra space.
  3. Your runtime complexity should be less than O(n2).
  4. There is only one duplicate number in the array, but it could be repeated more than once.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

思路:

这道题,老实说我只想到了肯定会超时的暴力解,然后查看了标准solution,发现用到了一个定理Floyd 判圈定理只要了解该定理,本题就变得很容易,

正如定理所说:“如果有限状态机或者链表上存在环,那么从同一起点以不同速度前进的两个指针必定会在某个时刻相遇”。这个定理可以判环,至于重复点,假设相遇点为M,那么令指针h从M出发,同时指针t从起点以相同的速度出发,那么相遇点就是环起点,也就是本题的重复点。


代码:

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int slow = 0;
        int fast = 0;
        while(true) {
            slow = nums[slow];
            fast = nums[nums[fast]];
            if(slow == fast) break;
        }
        int t = 0;
        while(true) {
            t = nums[t];
            slow = nums[slow];
            if(slow == t) break;
        }
        return slow;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值