题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1029
大意:从一个N元素的序列(N为奇数)中找出出现次数大于(N+1)/ 2 的元素。
思路:设答案为result。按照序列依次扫描,先把数组中第一个元素赋值给result,增加个计数器,cnt = 1;然后向右扫描,如果跟result相同,则cnt++,不同,那么cnt --。当cnt为0时,result换为当前的数。最后的result即为答案。
#include<cstdio>
#include<cstring>
#include<string>
#include<cctype>
#include<iostream>
#include<set>
#include<map>
#include<cmath>
#include<sstream>
#include<vector>
#include<stack>
#include<queue>
#include<algorithm>
#define fin(a) freopen("a.txt","r",stdin)
#define fout(a) freopen("a.txt","w",stdout)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
typedef long long LL;
using namespace std;
const int maxn = 1e6 + 10;
int result, cnt;
int main() {
int n, x;
while(scanf("%d", &n) == 1) {
cnt = 0;
while(n--) {
scanf("%d", &x);
if(cnt == 0) {
result = x;
cnt = 1;
}
else if(result == x) cnt++;
else cnt--;
}
printf("%d\n", result);
}
return 0;
}
本文介绍了一种高效算法,用于从含有奇数个元素的序列中找出出现次数超过(N+1)/2的元素。该算法通过遍历序列并使用计数器跟踪当前候选众数的方式实现。
1900

被折叠的 条评论
为什么被折叠?



