编程之美:水王问题及扩展

来源:互联网 发布:java api接口测试工具 编辑:程序博客网 时间:2024/05/02 01:22

题目描述:

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

扩展问题:

随着Tango的发展,管理员发现,“超级水王”没有了。统计结果表明,有3个发帖很多的ID,他们的发帖数目都超过了帖子总数目N的1/4。你能从发帖ID列表中快速找出他们的ID吗?

把数组分为四个四个数字一组的来看。由于a的发帖数超过了1/4,所以,平均下来,在每一个分组里都有一个a,并且至少在某一组中有大于一个的a,假如分组1中的四个数字都不相同,我们删除分组1,如果a不在分组1里面,那么在剩余的2~n组中,a出现的次数显然会继续大于1/4;如果a在分组1里面,那么在剩余2~n组中,平均下来,a还是会至少在每一个分组出现一次。所以只要分组1中4个数字不相同(主要是保证没有两个a),那么删除分组1,并不改变a在剩余数组中出现次数依然大于1/4的事实。同理b,c。

#include<iostream>#include<vector>using namespace std;int find1(vector<int>&id){    int a;    int ta=0;    int len = id.size();    for (int i = 0; i < len; i++){        if (ta == 0){            a = id[i];            ta = 1;        }        else{            if (a == id[i])                ta++;            else                ta--;        }    }    return a;}void find3(vector<int>&id){    int a, b, c;    int ta = 0, tb = 0, tc = 0;    int len = id.size();    for (int i = 0; i < len; i++){        if (ta == 0){            a = id[i];            ta = 1;        }        else if (a == id[i]){            ta++;        }        else if (tb == 0){            b = id[i];            tb = 1;        }        else if (b == id[i]){            tb++;        }        else if (tc == 0){            c = id[i];            tc = 1;        }        else if (c == id[i]){            tc++;        }        else{            ta--;            tb--;            tc--;        }    }    cout << a << endl << b << endl << c << endl;}int main(){    vector<int> id = { 1, 1, 2, 3, 1, 1 };    cout<<find1(id)<<endl;    vector<int> id2 = { 1, 1, 1, 2, 4, 2, 2, 3, 3, 3, 5 };    find3(id2);    return 0;}
0 0
原创粉丝点击