Task background:
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?
Design ideas:
The key to the problem is "water king" of the number of posts is more than half of the total number of posts, the post ID of the different two ID to eliminate, the remaining is "water king" ID;
Code implementation:
//looking for the water king//Letter 1405-1 class 20142966 Huang WeipengImportJava.util.Scanner; Public classFind { Public Static voidMain (string[] args) {//TODO Auto-generated method stubs intI,number; System.out.println ("Please enter the total number of posts:"); Scanner in=NewScanner (system.in); number=In.nextint (); intlist[]=New int[number]; System.out.println ("Please enter the ID of the post"); Scanner T=NewScanner (system.in); for(i=0;i<number;i++)//Assigning a value to an array{List[i]=T.nextint (); } intking=0,count=0;//compare two numbers if the same is added one, otherwise the cancellation for(i=0;i<number;i++) { if(count==0) {King=List[i]; } Else { if(king==List[i]) {Count++; } Else{Count--; }}} System.out.println ("The water King's ID is:" +king); }}
Realize:
Personal Summary:
There are several ways to achieve this problem, but the problem requires a quick find that the algorithm is simple, as long as the number of posts the most ID can be found, the problem may be distorted to:
How to quickly find the number with the most words in an array.
Find the Water king