Class practice-Finding water king

Source: Internet
Author: User

Title: Finding the Water king

Design ideas:

Suppose the first ID is the water king, with King record, the number of times recorded with the second, than the next ID if the same is times++, otherwise--; if times=0, the next one is designated as the Water King, and then proceed, the last times more than 0 that ID must be the water king, Because the number of occurrences is greater than half.

Code implementation:

Package test1; Public classforumking { Public Static voidMain (string[] args) {intid[]={1,1,4,1,1,8,1,7,5,1}; inttimes,king = id[0];  for(inti=times=0;i<Ten; i++)        {            if(times==0) {King=Id[i]; Times=1; }            Else            {                if(id[i]==King) Times++; Else Times--; }} System. out. println ("Water King's ID:"+king); }}

Realize:

Personal Summary:

See the topic is always feel impossible, but think of the words feel this is greater than half or very mysterious, the eye is here, feel this algorithm and the algorithm is very similar to the elimination, but temporarily can only think of so many.

Class practice-Finding water king

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.