How can we find second maximum from array efficiently?

前端 未结 16 1143
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:03

    // Set the first two different numbers as the maximum and second maximum numbers
    
     int max = array[0];
     int i = 1;
    //n is the amount of numbers
    
     while (array[i] == max && i < n) i++;
     int sec_max = array[i];
     if( max < sec_max ) {
        tmp = sec_max;
        sec_max = max;
        max = tmp;
     }
    
    //find the second maximum number
    
     for( ; i < n; ++i ) {
       if( array[i] > max ) {
         sec_max = max;
         max = array[i];
       } else if( array[i] > sec_max && array[i] != max ) {
         sec_max = array[i];
       }
     }
     printf("The second maximum number is %d\n", sec_max);
    

提交回复
热议问题