Find largest and second largest element in a range

后端 未结 11 2007
情歌与酒
情歌与酒 2020-12-10 07:30

How do I find the above without removing the largest element and searching again? Is there a more efficient way to do this? It does not matter if the these elements are dupl

11条回答
  •  春和景丽
    2020-12-10 07:40

    The optimal algorithm shouldn't need more than 1.5 * N - 2 comparisons. (Once we've decided that it's O(n), what's the coefficient in front of N? 2 * N comparisons is less than optimal).

    So, first determine the "winner" and the "loser" in each pair - that's 0.5 * N comparisons.

    Then determine the largest element by comparing winners - that's another 0.5 * N - 1 comparisons.

    Then determine the second-largest element by comparing the loser of the pair where the largest element came from against the winners of all other pairs - another 0.5 * N - 1 comparisons.

    Total comparisons = 1.5 N - 2.

提交回复
热议问题