one, the topic• Three people have designed a irrigation forum. 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?
Two, ideas
Idea 1: Because each person's ID number size is different, so the ID number of everyone can be sorted from small to large order, with fast sorting method, time complexity is: O (N*LOGN). It then iterates through the array, counting the number of occurrences of each ID number, and the number of occurrences more than half of the ID number is the request. The total time complexity is O (n*logn+n).
Idea 2: Because know the premise is that the water king post number of more than half of the total number of posts, therefore, all ID numbers from small to large sorting, as long as found in the middle of the array ID number, is definitely the ID number of the water king. The time complexity is reduced to O (N*logn) at this point.
Train of thought 3: We can use the mobile games we usually play the idea of a small star, if the next two adjacent ID number is different, it will be eliminated, because the number of water King post more than half of the total number of posts,
Therefore, the Water King ID number must be adjacent. This is the time complexity of O (N).
Three, code
#include <iostream>
using namespace Std;
int Shuiwang (int arr[], int length)
{
int result = Arr[0];
int t = 1;
for (int i = 1; i < length; ++i)
{
if (arr[i] = = result)
t++;
Else
t--;
if (t = = 0)
{
result = Arr[i];
t = 1;
}
}
t = 0;
for (i = 0; i < length; ++i)
{
if (arr[i] = = result)
t++;
}
return result;
}
int main ()
{
int a[10]={3,2,3,1,2,3,3,3,7,3};
int* N=a;
cout<< "Water King's ID number is:" <<shuiwang (a,9) <<endl;
return 0;
}
Four, the experimental results
Five, summary
In class, I think of only the first train of thought, then the students put forward the second way of thinking, finally in the program code optimization considerations, the teacher provides us with a third way of thinking. Through the help of teachers and classmates, finally completed the experiment, in the future experiment to widen their thinking
Classroom practice-searching for water kings