Find a number where it appears exactly N/2 times

后端 未结 20 1855
旧巷少年郎
旧巷少年郎 2021-01-29 23:17

Here is one of my interview question. Given an array of N elements and where an element appears exactly N/2 times and the rest N/2 elements are unique

20条回答
  •  清酒与你
    2021-01-29 23:53

    Algorithm RepeatedElement(a, n)

    while (true) do
    {
       i=Random() mod n+1; j=Random() mod n+1;
       // i and j are random numbers in the range [1,n]
       if ((i ≠ j) and a[i]=a[j])) then return;
    }
    

提交回复
热议问题