How can we find second maximum from array efficiently?

前端 未结 16 1168
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:05

    Step 1. Decide on first two numbers.
    Step 2. Loop through remaining numbers.
    Step 3. Maintain latest maximum and second maximum.
    Step 4. When updating second maximum, be aware that you are not making maximum and second maximum equal.

    Tested for sorted input (ascending and descending), random input, input having duplicates, works fine.

    #include 
    #define MAX 50
    int GetSecondMaximum(int* data, unsigned int size)
    {
        int max, secmax;
        // Decide on first two numbers
        if (data[0] > data[1])
        {
            max = data[0];
            secmax = data[1];
        }
        else
        {
            secmax = data[0];
            max = data[1];
        }
        // Loop through remaining numbers
        for (unsigned int i = 2; i < size; ++i)
        {
            if (data[i] > max)
            {
                secmax = max;
                max = data[i];
            }
            else if (data[i] > secmax && data[i] != max/*removes duplicate problem*/)
                secmax = data[i];
        }
        return secmax;
    }
    int main()
    {
        int data[MAX];
        // Fill with random integers
        for (unsigned int i = 0; i < MAX; ++i)
        {
            data[i] = rand() % MAX;
            std::cout << "[" << data[i] << "] "; // Display input
        }
        std::cout << std::endl << std::endl;
        // Find second maximum
        int nSecondMax = GetSecondMaximum(data, MAX);
        // Display output
        std::cout << "Second Maximum = " << nSecondMax << std::endl;
        // Wait for user input
        std::cin.get();
        return 0;
    }
    

提交回复
热议问题