寻找水王

Tango是微软亚洲研究院的一个试验项目。研究院的员工和实习生们都很喜欢在Tango上面交流灌水。传说,Tango有一大“水王”,他不但喜欢发贴,还会回复其他ID发的每个帖子。坊间风闻该“水王”发帖数目超过了帖子总数的一半。如果你有一个当 前论坛上所有帖子(包括回帖)的列表,其中帖子作者的ID也在表中,你能快速找出这个传说中的Tango水王吗?

 

问题相当于有一个数组,里面的数字超过一半是一样的,找出这个数字就可以。

假如每次删除两个不同的数(不管包括不包括最高频数),那么,在剩下的数字里,原最高频数出现的频率一样超过了50%,不断重复这个过程,最后剩下的将全是同样的数字,即最高频数。此算法避免的排序,时间复杂度只为O(N)。

 1 #include "stdio.h"
 2 #include <iostream>
 3 using namespace std;
 4 int shuiwang(int num[], int n)
 5 {
 6     int i;
 7     int candidate = 0;
 8     int count = 0;
 9     for (i = 0; i < n; i++)
10     {
11 
12        if (count == 0)
13 
14         {
15 
16             candidate = num[i];
17             count = 1;
18             cout<<""<<i+1<<"次比较  candidate="<<candidate<<endl;
19             //printf("%d candidate = %d \n", i, candidate);
20         }
21 
22         else
23 
24         {
25 
26             if (candidate == num[i])
27 
28             {
29 
30                 count++;
31                 cout<<""<<i+1<<"次比较 candidate="<<candidate<<"   count自增为"<<count<<endl;
32 
33             }
34 
35             else
36 
37             {
38                 count--;
39                 cout<<""<<i+1<<"次比较  candidate="<<candidate<<"   count自减为"<<count<<endl;
40                
41             }
42 
43         }
44     }
45 
46     return candidate;
47 
48 }
49 
50 int main()
51 
52 {
53 
54     int i, n, rs;
55 
56     int arr[] = {9,11,11,13,11,11,11,18,19,11,11,20,11};
57 
58     n = sizeof(arr)/sizeof(int);
59 
60     rs = shuiwang(arr, n);
61 
62     cout<<"水王是"<<rs<<endl;
63 
64 }

运行截图:

 

 

posted @ 2016-05-20 14:52  卿语  阅读(192)  评论(0编辑  收藏  举报