How can we find second maximum from array efficiently?

前端 未结 16 1139
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条回答
  •  旧时难觅i
    2020-12-25 14:55

    Other way to solve this problem, is to use comparisons among the elements. Like for example,

    a[10] = {1,2,3,4,5,6,7,8,9,10}
    

    Compare 1,2 and say max = 2 and second max = 1

    Now compare 3 and 4 and compare the greatest of them with max.

    if element > max
         second max = max
         element = max
    else if element > second max
         second max = element
    

    The advantage with this is, you are eliminating two numbers in just two comparisons.

    Let me know, if you have any problem understanding this.

提交回复
热议问题