Title: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?
Requirements:Time Complexity of O (n)
First, design ideas
(1) Enter the Post ID record form
(2) Start with the first ID, and follow the post ID to compare, if the same counter plus one, or minus one. If the value of the counter is reduced to zero, the current ID is re-selected to start the record comparison.
(3) Output results
Second, the source code
Press CTRL + C to copy the codeShuiwang.cpp:Defines the entry point for the console application.//#include "stdafx.h" #include "iostream.h" #define MA Xsize 20void findwater (int id[],int len,int &water) {int counter=0; counter for (int i=0;i<len;i++) {if (counter==0)//If counter is zero {water=id[i]; Record the current post ID as the water king suspect counter++; } else {if (Water==id[i])//Joshuis suspect is the same as the following ID counter++; Counter record down, otherwise minus one else counter--; }}}int Main (int argc, char* argv[]) {int id[maxsize]; Post record form int num,waterking; Number of postings, water King cout<< "Please enter the number of posts:"; cin>>num; cout<< "Please enter the Post ID:"; for (int i=0;i<num;i++) {cin>>id[i]; } findwater (id,num,waterking); cout<< "Water King is:" <<WaterKing<<endl; return 0;}Press CTRL + C to copy the code
Third, the experiment
Iv. Personal Summary
The beginning of the understanding of the topic is not very thorough, in the teacher class after a little hint to understand the general meaning of the topic, according to the general idea is each traversal, but the time complexity will be very large, there must be more simple method, after thinking, you can compare the adjacent two numbers, The same words are kept, not the same, clear one, follow this idea to go on, slowly have the answer.
Find the Water king