Find any one of multiple possible repeated integers in a list

前端 未结 6 471
一生所求
一生所求 2021-01-02 02:18

Given an array of n+1 integers, each in the range 1 to n, find an integer that is repeated.

I was asked this at a job intervi

6条回答
  •  -上瘾入骨i
    2021-01-02 02:40

    We use circle detection's idea to solve this problem.

    All we need to do is first find the begin of the circle and then find the duplicated one in the circle.

    Here's the code in c++:

    int findDuplicate(vector& 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;
    }
    

提交回复
热议问题