Find the second largest number in a shaped array

Source: Internet
Author: User

How to find the second largest number in the array in time complexity O (n)?

By setting two variables, one holds the maximum value, one holds the second largest value, and by the process of finding the maximum value, the original maximum is gradually changed to the second largest value. One implementation code is as follows (Java edition):

1 /**2 * Find the second largest number of arrays in time complexity O (n)3  * @authorJiajoa4  *5  */6  Public classAlgorithm_getsecondmax {7 8      Public Static voidMain (string[] args) {9         //TODO auto-generated Method StubTen         int[] data = {3,2,5,1,6,4,7}; One System.out.println (Algorithm_getsecondmax.getsecondmax (data)); A     } -      -     //by setting two variables, one holds the maximum value, one holds the second largest value, the     //by the process of finding the maximum value, the original maximum value gradually becomes the second largest value, -      Public Static intGetsecondmax (int[] data) { -         intFirst_max = data[0]; -         intSecond_max =Integer.min_value; +          for(inti=1;i<data.length;i++){ -             if(data[i]>First_max) { +Second_max =First_max; AFirst_max =Data[i]; at}Else{ -                 if(data[i]>Second_max) -Second_max =Data[i]; -             } -         } -         returnSecond_max; in     } -}

Find the second largest number in a shaped array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.