287. Find the Duplicate Number

Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] inclusive.

There is only one duplicate number in nums, return this duplicate number.

Follow-ups:

  1. How can we prove that at least one duplicate number must exist in nums
  2. Can you solve the problem without modifying the array nums?
  3. Can you solve the problem using only constant, O(1) extra space?
  4. Can you solve the problem with runtime complexity less than O(n2)?

 

Example 1:

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

Example 2:

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

Example 3:

Input: nums = [1,1]
Output: 1

Example 4:

Input: nums = [1,1,2]
Output: 1

 

Constraints:

  • 2 <= n <= 3 * 104
  • nums.length == n + 1
  • 1 <= nums[i] <= n
  • All the integers in nums appear only once except for precisely one integer which appears two or more times.
class Solution {
public:
    //二分。数组中仅有一个数字是重复的,但是可能重复多次,比如:2 2 2 2
    //二分:查找大于中间数的数有多少个,小于中间数的数有多少个.
    //关键     数组中最大数最大可能是n,但不一定是n。
    int findDuplicate(vector<int>& nums) {
        int  Min = 1,Max = nums.size()-1;
        //1 3 4 2 2
        while(Min <= Max){
            int cnt = 0;
            int mid = Min + (Max-Min)/2;
            for(int i=0;i<nums.size();i++){
                if(nums[i] <= mid){
                    cnt++;
                }
            }
            if(cnt > mid){
                Max = mid-1;
            }else{
                Min = mid+1;
            }
        }
        return Min;
    }
};

 

 

//类似链表有环的解法:1 3 4 2 2 可以看出一个链表  1->3->4->(2 --2)。那么即可用户链表有环,求环的入口来解

//数组  [1,3,4,2,2]   nums[0] = 1  ;  nums[1] = 3 ;  nums[3] = 2 ;  nums[2] = 4; nums[4] = 2 ......

//下标也可以类似快慢跑   nums[nums[0]] = 3;   nums[nums[3]] = 4;  nums[nums[4]] = 4 ;

//在4相遇  环是2--4---2。然后求环的入口

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

 

posted on 2020-11-18 23:15  wsw_seu  阅读(105)  评论(0编辑  收藏  举报

导航