C solution O(n) beat 75% solution


  • -8
    M

    int findDuplicate(int* a, int numsSize) {

    int i=0;
    
    while(i<numsSize)
    {
        while(a[i] != (i+1))
        {
            if(a[a[i]-1] == a[i])
                return a[i];
            else
            {
                //swap a[a[i]-1] and a[i]
                a[a[i]-1] = a[i] + a[a[i]-1] - (a[i] = a[a[i]-1]);
            }
        }
        i++;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.