leetcode 287. Find the Duplicate Number(二分/快慢指针)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/huatian5/article/details/83015801

1.二分方法
因为数字是1~n,所以我们可以根据小于mid的数目来判断重复的数字是在左边还是右边

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

2.快慢指针
类似于142. Linked List Cycle II

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){
                fast = 0;
                while(fast != slow){
                    fast = nums[fast];
                    slow = nums[slow];
                }
                return slow;
            }
        }
        return 0;
    }
};

猜你喜欢

转载自blog.csdn.net/huatian5/article/details/83015801