A three-person line designed a forum for irrigation. 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?
1. Design Ideas
Because the number of "water king" posts more than half, will be adjacent to 22 different IDs eliminated, then the remaining "Water king" ID. Use a one-dimensional array a[] to store all IDs, so that "water king" ID is the first a[0 in the array, with an integer J record the number of water King ID occurrences, the adjacent number is the same as J + +, the difference is J-, and if the j<=0, then the water king for the ID, cycle judgment until the end of the cycle
Source:
1 PackageShuiwang;2 ImportJava.util.*;3 4 Public classFind_shuiwang {5 6 Public Static voidMain (string[] args) {7 //TODO auto-generated Method Stub8find_function function =Newfind_function ();9Scanner sca=NewScanner (system.in);TenSystem.out.println ("Enter Number of posts:"); One intn=sca.nextint (); AString post[]=NewString[n+1]; - - inti; theSystem.out.println ("Enter Post ID:"); - for(i=0;i<n+1;i++) - { -post[i]=sca.nextline (); + } -String Shuiwang =Function.find (post, n); +System.out.println ("Water King ID is" +Shuiwang); A } at -}Main
1 PackageShuiwang;2 3 Public classfind_function {4String find (string[] post,intN)5 {6 intI,j = 0;7String Shuiwang = post[0];//make the first id a water king8 for(i=0;i<n;i++)9 { Ten if(!shuiwang.equals (Post[i])) One { AJ=j-1; - if(j<=0)//if j=0, the previous ID must have more than half of the water king, so the elimination of at most half of the water king - { theSHUIWANG=POST[I+1];//continue searching in the remaining IDs -J=1;//redefining water King ID occurrences -i++; - } + } - Else + { Ashuiwang=Post[i]; atj=j+1;//number of water king posts - } - } - returnShuiwang; - } -}find_function
Results:
Software Engineering Exercises--Find the Water king