Tango is a pilot project in Microsoft Research Asia. The staff and interns at the Institute are very fond of exchanging water on tango. Legend has it that Tango has a big "water king", he not only likes to post, but also reply to the other ID issued by each post. Rumor has it that the "water king" posted more than half the total number of posts. If you have a list of all posts (including replies) on the current forum, and the ID of the post author is also in the table, can you quickly find out the legendary tango water king?
Method One: Brute Force solution
For each ID, traverse the entire list, counting the number of occurrences, if more than half, the "Water King" is found. Complexity O (n2).
The reference code is as follows:
1 intFind (vector<int>ID)2 {3 intRET =-1; 4 intLen =id.size ();5 intCNT = len/2; 6 for(inti =0; I <= CNT; i++)7 {8 intCnti =1; 9 for(intj = i+1; J < Len; J + +)Ten if(Id[j] = = Id[i]) cnti++; One if(Cnti >CNT) A { -RET =Id[i]; - Break; the } - } - returnret; -}
View Code
Method Two: Sort
Sort all the IDs first. If an ID appears more than half of the total number of occurrences, then the N/2 item in this ordered ID list must be this ID. Complexity O (NLOGN).
The reference code is as follows:
1 int Find (vector<int> id)2{3 4 return id[id.size ()/25 }
View Code
Method Three: Linear time algorithm
If you delete two different IDs at a time, the "Water King" ID will appear more than half the total in the remaining list of IDs. You can get an answer by continually repeating the process by reducing the total number of IDs in the ID list. The reference code looks like this:
1 intFind (vector<int>ID)2 {3 intRET, Len =id.size ();4 for(inti =0, n =0; i < Len; i++)5 {6 if(n = =0)7 {8RET =Id[i];9n++; Ten } One Else A { - if(ret = = Id[i]) n++; - Elsen--; the } - } - returnret; -}
View Code
Scaling issues
With the development of Tango, the administrator found that "super Water King" did not. The statistics show that there are 3 posts with many IDs, and they post more than 1/4 of the total number of postings. Can you quickly find their ID from the list of post IDs?
The "answer" reference code is as follows:
1vector<int> Find (vector<int>ID)2 {3vector<int> Ret (3, -1); 4 5 intN0 =0, N1 =0, N2 =0, Len =id.size ();6 for(inti =0; i < Len; i++)7 {8 if(Id[i] = = ret[0]) n0++; 9 Else if(Id[i] = = ret[1]) n1++; Ten Else if(Id[i] = = ret[2]) n2++; One Else if(N0 = =0) A { -N0 =1; -ret[0] =Id[i]; the } - Else if(N1 = =0) - { -N1 =1; +ret[1] =Id[i]; - } + Else if(N2 = =0) A { atN2 =1; -ret[2] =Id[i]; - } - Else - { -n0--; inn1--; -n2--; to } + } - returnret; the}
View Code
"The beauty of programming" looking for a post "water king"