How can we find second maximum from array efficiently?

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

    You need a second test:

     for(int i=0;i<5;i++){  
       if(arr[i]>max){  
         second_max=max;  
         max=arr[i];            
       }
       else if (arr[i] > second_max && arr[i] != max){
         second_max = arr[i];
       }
     }
    

提交回复
热议问题