• Three people have designed a irrigation forum. Information college students like to exchange irrigation above, legend in the forum there is a "water king", he not only likes to post, but also reply to other ID issued by each post. The "Water King" has been rumored to have posted more than half the number of posts. • If you have a list of posts (including replies) for the current forum, and the ID of the author of the Post is in it, can you quickly find the legendary water king?
• With the development of the Forum, the administrator found that the water king did not, but the statistical results show that there are three posts a lot of IDs. According to the statistics of their posts more than 1/4, you can quickly find them from the list of posts? Design ideas before the "Water King" post number of more than half of the number of posts, so directly to find more than half of the number of posts ID can, this time to find the second "water king" only need to put the list of the ID to remove the original "Water King", again look for can. Code implementation:
1 Packagefinding;2 Importjava.util.InputMismatchException;3 ImportJava.util.Scanner;4 5 Public classFinding {6 Public Static voidMain (string[] args) {7 //TODO Auto-generated method stubs8 for(intM=0;;)9 {Ten intBug=0; OneScanner sc =NewScanner (system.in); ASystem.out.println ("Please enter the number of IDs:"); - intn=sc.nextint (); -System.out.println ("Please enter an ID (for an integer):"); the intid[]=New int[n]; - Try //Capturing input Errors - { - for(inti=0;i<n;i++) + { -id[i]=sc.nextint (); + } A } at Catch(inputmismatchexception e) - { -SYSTEM.OUT.PRINTLN ("The input is illegal! Please enter an integer! "); -Bug=1; - } - if(bug!=1) in { - intshuiwang[]=New int[2]; to for(intl=0;l<2;l++) + { -SHUIWANG[L]=ID[0];//starting with the first ID, the first one is the water king. the intTemp=1; * for(inti=0;i<n-1;i++) $ {Panax Notoginseng for(intj=i+1;j<n;j++) - { the if(Shuiwang[0]==id[j])//when the water king is at the same time as the next ID, the counter temp+1 + { Atemp++; the } + } - if(TEMP<=N/2) $ { $SHUIWANG[0]=ID[I+1];//when temp is less than half of the total number of posts, replace an ID for temporary water king - } - } the for(inti=0;i<n-temp;i++) - {Wuyi for(intj=0;j<n;j++) the { - if(id[j]!=shuiwang[0]) Wu { -id[i]=Id[j]; About Break; $ } - - } - } An=n-temp; + } theSystem.out.println ("The Water King is (the number of posts more than half the total number of stickers):" +shuiwang[0]+ "" +shuiwang[1]); - } $System.out.println ("Continue looking for water King please press N, exit Please enter S:"); theString s=Sc.next (); the if(S.equals ("s")) theSystem.exit (0); the Else - Continue; in sc.close (); the } the About } the}
:
Software Engineering Personal work