Find the Duplicate Number数组中重复的数

这是一篇关于解决数组中存在重复数问题的博客。通过两种方法来找出数组中1到n之间的重复数值:一是使用二分搜索策略,通过统计小于等于中间值的数出现的次数来逐步缩小范围;二是利用快慢指针,模拟链表的环形查找,找到循环的起点即为重复的数。
摘要由CSDN通过智能技术生成
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) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.

题意:数组中有1+n个数都是1到n之间,找出其中重复的。
解法一:二分搜索,先求出中点mid,然后遍历整个数组,统计所有小于等于mid的数的个数,如果个数小于等于mid,则说明重复值在[mid+1, n]之间,反之,重复值应在[1, mid-1]之间。

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int left = 0, right = nums.size();
        while(left < right){
            int mid = left + (right - left) / 2;
            int cnt = 0;
            for(int num : nums){
                if(num <= mid)
                    cnt++;
            }
            if(cnt <= mid) left = mid + 1;
            else right = mid;
        }
        return right;
    }
};

解法二:利用快慢指针,思路和带环链表那一题一样,因为数组中只有1到n之间的数,使得数组下标和值可以跳转,例如样例1中的[1 3 4 2 2]数组元素的跳转在这里插入图片描述
最后肯定会碰到循环,此时利用之前带环链表求入口的思路就能求得开始循环的那个值,也就是重复的。

class Solution {
public:
    int findDuplicate(vector<int>& nums) {
        int slow = 0, fast = 0, slow2 = 0;
        while(true){
            slow = nums[slow];
            fast = nums[nums[fast]];
            if(slow == fast){
                while(slow != slow2){
                    slow = nums[slow];
                    slow2 = nums[slow2];
                }
                return slow;
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值