Puzzle : finding out repeated element in an Array

后端 未结 9 1063
面向向阳花
面向向阳花 2021-02-10 17:39

Size of an array is n.All elements in the array are distinct in the range of [0 , n-1] except two elements.Find out repeated element without using extra temporary array with con

9条回答
  •  青春惊慌失措
    2021-02-10 18:21

    Based on @sje's answer. Worst case is 2 passes through the array, no additional storage, non destructive.

    O(n) without the temp array.

    a[]={1,0,0,2,3};
    i=0;
    int required;
    while (a[a[i] % n] < n)    
       a[a[i++] % n] += n;
    
    required = a[i] % n;
    while (i-->0)
       a[a[i]%n]-=n;
    
    print required;
    

    (Assuming of course that n < MAX_INT/2)

提交回复
热议问题