数组-寻找重复的数-中等

描述
给出一个数组 nums 包含 n + 1 个整数,每个整数是从 1 到 n (包括边界),保证至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。


1.不能修改数组(假设数组只能读)
2.只能用额外的O(1)的空间
3.时间复杂度小于O(n^2)
4.数组中只有一个重复的数,但可能重复超过一次


您在真实的面试中是否遇到过这个题?  
样例
给出 nums = [5,5,4,3,2,1],返回 5.

给出 nums = [5,4,4,3,2,1],返回 4.


题目链接

程序 


class Solution {
public:
    /**
     * @param nums: an array containing n + 1 integers which is between 1 and n
     * @return: the duplicate one
     */
    // 由于数组大小n+1,元素的取值范围1~n,可以建立下标到数组元素的映射,
    // 同时数组元素也可以作为下标,例如{1,2,3,1},映射关系为{0,3}->1,1->2,2->3,会形成环。 
    int findDuplicate(vector<int> &nums) {
        // write your code here
        int slow, fast;
        slow = fast = 0;
        do{
           slow = nums[slow];
           fast = nums[nums[fast]];
        }while(fast != slow);
        fast = 0;
        while(slow != fast){
            slow = nums[slow];
            fast = nums[fast];
        }
        return fast;
    }
};



猜你喜欢

转载自blog.csdn.net/qq_18124075/article/details/80918638