How can we find second maximum from array efficiently?

前端 未结 16 1076
Happy的楠姐
Happy的楠姐 2020-12-25 14:39

Is it possible to find the second maximum number from an array of integers by traversing the array only once?

As an example, I have a array of five integers from whi

16条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-25 15:08

    The upper bound should have be n+log2⁡n−2, but it bigger than O(n) in case of random selection algorithm, but in worst case it much smaller. The solution might be

    1. build a tree like to find the MAX element with n - 1 comparisons

      max(N) / \ max(N/2) max(N/2)

    2. remove the MAX and find the MAX again log2n - 1 comparison

    PS. It uses additional memory, but it faster than random selection algorithm in worst case.

提交回复
热议问题