How can we find second maximum from array efficiently?

前端 未结 16 1078
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 14:56

    How about the following below. make_heap is O(n) so this is efficient and this is 1-pass We find the second max by taking advantage that it must be one of the heap children of the parent, which had the maximum.

    #include 
    #include 
    
    int main()
    {
        int arr[6]={0,1,2,3,4,5};
    
        std::make_heap(arr, arr+6);
        std::cout << "First Max: " << arr[0] << '\n';
        std::cout << "Second Max: " << std::max(arr[1], arr[2]) << '\n';
        return 0;
    }
    

提交回复
热议问题