How can we find second maximum from array efficiently?

前端 未结 16 1173
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

    Here you are:

    std::pair GetTwoBiggestNumbers(const std::vector& array)
    {
        std::pair biggest;
        biggest.first = std::max(array[0], array[1]);  // Biggest of the first two.
        biggest.second = std::min(array[0], array[1]); // Smallest of the first two.
    
        // Continue with the third.
        for(std::vector::const_iterator it = array.begin() + 2;
            it != array.end();
            ++it)
        {
            if(*it > biggest.first)
            {
                biggest.second = biggest.first;
                biggest.first = *it;
            }
            else if(*it > biggest.second)
            {
                biggest.second = *it;
            }
        }
    
        return biggest;
    }
    

提交回复
热议问题