• 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;
        }
    };
  • 相关阅读:
    Oracle Time Model Statistics(时间模型统计)
    IBAction:IBOutlet:注意事项
    函数何时值传递,何时指针,何时引用传递总结
    更新客户配置文件
    UML的通用机制(三)
    数学之路-数据分析进阶-区间预计与如果检验(2)
    android应用开发-从设计到实现 3-3 Sketch静态原型设计
    测试MongoDB的自动分片
    详解MongoDB中的多表关联查询($lookup) (转)
    mongodb移除分片和添加分片(转)
  • 原文地址:https://www.cnblogs.com/wsw-seu/p/14002860.html
Copyright © 2020-2023  润新知