How can we find second maximum from array efficiently?

前端 未结 16 1136
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:10

    Here is something which may work ,

    public static int secondLargest(int[] a){
        int max=0;
        int secondMax=0;
    
        for(int i=0;i<a.length;i++){
            if(a[i]<max){
                if(a[i]>secondMax){
                    secondMax=a[i];
                }
                continue;
            }
    
            if(a[i]>max){
                secondMax=max;
                max=a[i];
            }
    
        }
        return secondMax;
    }
    
    0 讨论(0)
  • 2020-12-25 15:12
    int max,secondMax;
    max=secondMax=array[0];
                                                    for(int i=0;i<array.length;i++)
        {                                                   if(array[i]>max)                                                    {                                           max=array[i];                                                   }
                                                            if(array[i]>secondMax && array[i]<max)                                                  {
        secondMax=array[i];                                                 }
        }
    
    0 讨论(0)
  • 2020-12-25 15:12
    #include <iostream>
    using namespace std;
    
    int main() {
    
       int  max = 0;
        int sec_Max = 0;
    
        int array[] = {81,70,6,78,54,77,7,78};
    
        int loopcount = sizeof(array)/sizeof(int);
    
        for(int i = 0 ; i < loopcount ; ++i)
        {
    
            if(array[i]>max)
            {
                sec_Max = max;
                max = array[i];
            }
    
            if(array[i] > sec_Max && array[i] < max)
            {
                sec_Max = array[i];
            }
        }
    
        cout<<"Max:" << max << " Second Max: "<<sec_Max<<endl;
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-25 15:14

    The easiest solution would be to use std::nth_element.

    0 讨论(0)
提交回复
热议问题