1. Topics
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?
2. Ideas
To be implemented in an O (n) time complexity, the method used is to set the Count K, set shui=a[0] Compare shui and a[i], if the two numbers are not the same, skip this number and K-1, if the same set k++, when k<0 reset Shui=a[i+1], After the loop, you can get the water King ID Shui
3. Code
//#include <stdafx.h>#include <iostream.h>intMainintargcChar*argv[]) { inta[ -]; intTienum; inti,j,k=1; intshui; cout<<"Please enter the total number of posts:"; CIN>>Tienum; cout<<Endl; for(i=0; i<tienum;i++) {cout<<"Please enter section"<<i+1<<"ID of a post:"; CIN>>A[i]; } Shui=a[0]; for(i=1; i<tienum;i++) { if(shui!=A[i]) {k=k-1; if(k<0) {Shui=a[i+1]; K=1; I++; } } Else{Shui=A[i]; K=k+1; }} cout<<"The Water King ID is:"<<shui<<Endl; return 0; }
4.
5. Summary
The idea is very ingenious, I have thought of the identification of duplicate ID to do with the next duplicate ID to do a comparison processing, after reading someone else's blog to be inspired, you can count the number of repetitions to compare.
Classroom exercises-finding water kings