Classroom Practice--"Find the water king continued"

Source: Internet
Author: User

Design ideas:

① as in the last train of thought, simplify the problem to find the 3 most frequently occurring number of occurrences from an array.

② will "22 phase elimination" Mode of thinking into "31 phase elimination"

③ initializes time to zero, Kingid is zero, then assigns values sequentially, encounters the same time1+1 as KINGID1, the remaining two are the same, and encounters all time-1 that differ from three.

Code:

Import java.util.*; Public classFindthreenum { Public Static voidMain (string[] args) {Scanner input=NewScanner (System.inch); System. out. println ("Please enter the length of the array:"); intLength =Input.nextint (); int[] id =New int[length]; System. out. println ("Please enter an array:");  for(intI=0; i<length;i++) {Id[i]=Input.nextint ();                } input.close (); intkingid1=0; intKingid2=0; intkingid3=0; inttime1=0; intTime2=0; inttime3=0;  for(intI=0; i<length;i++)        {            if(time1==0&& Id[i]!=kingid2 && id[i]!=kingid3) {KINGID1=Id[i]; Time1++; }            Else if(time2==0&& id[i]!=kingid1 && id[i]!=kingid3) {Kingid2=Id[i]; Time2++; }            Else if(time3==0&& id[i]!=kingid1 && id[i]!=Kingid2) {KINGID3=Id[i]; Time3++; }            Else if(Id[i]!=kingid1 && Id[i]!=kingid2 && id[i]!=kingid3) {time1--; Time2--; Time3--; }            Else if(id[i]==kingid1) {time1++; }            Else if(id[i]==Kingid2) {time2++; }            Else if(id[i]==kingid3) {Time3++; }} System. out. println ("The Water kings were:"+ KINGID1 +","+ Kingid2 +","+kingid3); }}

Results:

Summarize:

This class of practice compared to the last time to feel bad, that is, the number of times to change from one to three, so still take the last thought to do it is not very difficult.

Classroom Practice--"Find the water king continued"

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.