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 ideasAccording to the requirements of the topic, this program can only use a for loop, according to the method of sorting and searching, time complexity is O (NLGN), so this method cannot be used. Because "Water king" posts have been over half, so when there are different ID posts, directly removed, the last remaining ID is definitely "water king". Second, the source code
#include <iostream.h>
int main ()
{
int I,j,k=1,shuiwang;
int a[10]={1,2,3,3,3,3,5,4,6,3};
SHUIWANG=A[0];
for (i=1;i<10;i++)
{
if (Shuiwang!=a[i])
{
K=k-1;
if (k<=0)
{
SHUIWANG=A[I+1];
I=s;
i++;
}
}
Else
{
Shuiwang=a[i];
k=k+1;
}
}
cout<< "Water King ID:" <<shuiwang<<endl;
return 0;
}
Iii. Results of operation
Iv. Personal Summary
At the beginning, because the input ID also takes time complexity, plus the program needs to run, the time complexity will be greater than O (n), so I canceled the input link, directly to enter the content into the source code, so that can meet the requirements of time complexity. The requirements of this exercise are very clear, only need to find the Water King ID, the other do not consider, very targeted.
Classroom Practice--Find the Water king