How can we find second maximum from array efficiently?

前端 未结 16 1141
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 15:01

    Check this solution.

    max1 = a[0];
    max2 = a[1];
    
    for (i = 1; i < n; i++)
    {
        if (max1 < a[i])
        {
            max2 = max1;
            max1 = a[i];
        }
    
        if (max2 == max1) max2 = a[i + 1];
    
        if (max2 == a[n])
        {
            printf("All numbers are the same no second max.\n");
            return 0;
        }
    
        if (max2 < a[i] && max1 != a[i]) max2 = a[i];
    }
    

提交回复
热议问题