大小为N的数组A,其主要元素是一个出现次数超过N/2的元素。找出主要元素。

数据结构与算法分析——c语言描述 练习2.19 答案


这道题网上找的答案然后自己写一遍。参考了阿飞旭日东升的代码


这道题的算法为什么数组B的候选元也是A的候选元呢?我不知道怎么数学证明。以下只是个人吹水,如果a中找到一个候选元,b中一个元素代表a中的2个元素,就算是最坏的情况下排列为xyxyxyxyxy ,要提取候选元,最后肯定是要加上两个xx。主要元素的候选元肯定是最多的。


#include<stdio.h>

#define MAXN 1000

int a[MAXN], b[MAXN];


bool IsMainCell(int *a, int n, int probable) {
	int cnt = 0;
	for (int i = 0; i < n; i++)
		if (a[i] == probable)
			cnt++;
	if (cnt > n / 2)
		return true;
	else
		return false;
}

int FindMainCell(int a[], int b[], int n, int n2) {
	if (n == 0)
		return -1;
	if (n == 1)
		if (IsMainCell(b, n2, a[0]))
			return a[0];
		else
			return -1;
	int cnt = 0;
	for (int i = 0; i + 1 < n; i++) {
		if (a[i] == a[i + 1]) {
			b[cnt++] = a[i];
		}
	}
	int res = FindMainCell(b, a, cnt, n);
	if (res == -1 && n % 2 == 1 && IsMainCell(a, n, a[n - 1]))
		return a[n - 1];
	else
		return res;
}

int main() {
	int n;
	scanf("%d", &n);
	for (int i = 0; i < n; i++)
		scanf("%d", &a[i]);


	int temp = FindMainCell(a, b, n, 0);
	if (temp == -1)
		printf("no");
	else
		printf("%d", temp);
}


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值