Algorithm to find two repeated numbers in an array, without sorting

前端 未结 24 2161
南方客
南方客 2020-11-28 06:58

There is an array of size n (numbers are between 0 and n - 3) and only 2 numbers are repeated. Elements are placed randomly in the array.

E.g. in {2, 3, 6, 1, 5, 4

24条回答
  •  不知归路
    2020-11-28 07:33

    Here is an algorithm that uses order statistics and runs in O(n).

    You can solve this by repeatedly calling SELECT with the median as parameter.

    You also rely on the fact that After a call to SELECT, the elements that are less than or equal to the median are moved to the left of the median.

    • Call SELECT on A with the median as the parameter.
    • If the median value is floor(n/2) then the repeated values are right to the median. So you continue with the right half of the array.
    • Else if it is not so then a repeated value is left to the median. So you continue with the left half of the array.
    • You continue this way recursively.

    For example:

    • When A={2, 3, 6, 1, 5, 4, 0, 3, 5} n=9, then the median should be the value 4.
    • After the first call to SELECT
    • A={3, 2, 0, 1, <3>, 4, 5, 6, 5} The median value is smaller than 4 so we continue with the left half.
    • A={3, 2, 0, 1, 3}
    • After the second call to SELECT
    • A={1, 0, <2>, 3, 3} then the median should be 2 and it is so we continue with the right half.
    • A={3, 3}, found.

    This algorithm runs in O(n+n/2+n/4+...)=O(n).

提交回复
热议问题