leetcode287. 寻找重复数(二分 链表 快慢指针)

链接:https://leetcode-cn.com/problems/find-the-duplicate-number/

题目

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

假设 nums 只有 一个重复的整数 ,找出 这个重复的数 。

你设计的解决方案必须不修改数组 nums 且只用常量级 O(1) 的额外空间。

用例

示例 1:

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

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

输入:nums = [1,1]
输出:1
示例 4:

输入:nums = [1,1,2]
输出:1

提示:

1 <= n <= 105
nums.length == n + 1
1 <= nums[i] <= n
nums 中 只有一个整数 出现 两次或多次 ,其余整数均只出现 一次

进阶:

如何证明 nums 中至少存在一个重复的数字?
你可以设计一个线性级时间复杂度 O(n) 的解决方案吗?

题目

方法一
对[1,n]区间 二分查找
然后取mid 判断 nums数组中大于mid的数有几个 数量超过mid则在区间左侧继续二分
反之则在右侧二分

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int n=nums.size();
        int l=1,r=n-1;
        while(l<=r){
            int mid=(l+r)/2;
            int cnt=0;
            for(int i=0;i<n;++i){
                if(nums[i]<=mid)
                    cnt++;
            }
            if(cnt<=mid){
                l=mid+1;
            }else{
                r=mid-1;
            }
        }
        return l;
    }
};

方法2
问题其实可以映射为链表
因为每个数都在[1,n]区间中 因此可以将值作为索引映射到链表上 出现重复值即链表中存在环 问题就转变为环形链表求环起点问题(https://leetcode-cn.com/problems/linked-list-cycle-ii/)
因此用快慢指针解决
具体思路如该博客:https://www.cnblogs.com/kitamu/p/15246876.html

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int fast=0,slow=0;
        while(true){
            fast=nums[nums[fast]];
            slow=nums[slow];
            if(fast==slow)
                break;
        }
        fast=0;
        while(slow!=fast){
            slow=nums[slow];
            fast=nums[fast];
        }
        return fast;
    }
};
posted @ 2021-10-22 14:39  kitamu  阅读(47)  评论(0)    收藏  举报
Live2D