主元素问题(C语言)
题目
参考代码
#include <stdio.h>
int main()
{// 主元素问题int n, s[400002], num = 1, max = 0, maxNum = 0;scanf("%d", &n);for (int i = 0; i < n; i++)scanf("%d", &s[i]);for (int i = 0; i < n; i++) // 冒泡排序for (int j = 0; j < n - i; j++)if (s[j] > s[j + 1]){int t = s[j];s[j] = s[j + 1];s[j + 1] = t;}int m;for (m = 1; m < n; m++){if (s[m] == s[m - 1])num++;else{if (num > (n / 2) && num > maxNum){max = s[m - 1];maxNum = num;}num = 1;}}if (maxNum == 0)printf("0");elseprintf("%d", max);return 0;
}