C语言:数组中出现次数超过一半的数字

数组长度的计算

int a[] = {1,1,1,1,1,1,1,1};
int len = sizeof(a)/sizeof(int);

sizeof(a)函数计算a的字节数,sizeof(int)函数计算int类型的字节数,因此两数相除才是数组a的长度。

循环遍历数组

与字符串不同,数组的遍历不能使用p++的方式,否则无法正确终止循环。
例如:

#include<stdio.h>

int numMorethanHalf(int *a) {
	
	int count = 0;

	while(a != NULL) {
		count++;
		a++;
		
	}

	return count;

}

void test1() {    
	int a[] = { 1,3,4,8,2,3,3,3 };

	int result = numMorethanHalf(&a);

	printf("%d\n", result);
}

int main() {

	test1();
	
}

此代码使程序陷入死循环,无法结束。也就说明a != NULL恒成立。

解决上述两个问题后,就可以写该问题的核心代码:

int numMorethanHalf(int *a,int len) {
	if ((a == NULL) || (len <= 0))
		return -1;
	int result = a[0];
	int count = 1;

	for (int i = 0; i < len - 1;i++) {

		if (result == a[i+1]) {
			count++;
		}
		else if( (result != a[i + 1]) && (count > 1) ){
			count--;
		}
		else{
			result = a[i + 1];
			count = 1;
		}		
	}

	count = 0;

	for (int i = 0; i < len; i++) {
		if (a[i] == result)
			count++;
	}
	if (count * 2 < len)
		return -2;

	return result;
}

测试函数:

void test1() {    //存在超过数组长度一半的数字
	int a[] = { 1,3,4,8,2,3,3,3 };

	int len = sizeof(a) / sizeof(int);

	int result = numMorethanHalf(&a,len);

	printf("%d\n", result);
}


void test2() {    //不存在超过数组长度一半的数字
	int a[] = { 1,3,4,8,2,2,3,3 };

	int len = sizeof(a) / sizeof(int);

	int result = numMorethanHalf(&a, len);

	printf("%d\n", result);
}

void test3() {    //指针为空

	int result = numMorethanHalf(0, 0);

	printf("%d\n", result);
}

void test4() {   //超过数组长度一半的数字在前半段
	int a[] = { 1,1,1,1,1,2,3,3,4};

	int len = sizeof(a) / sizeof(int);

	int result = numMorethanHalf(&a, len);

	printf("%d\n", result);
}

void test5() {   //超过数组长度一半的数字在后半段
	int a[] = { 1,0,4,8,3,3,3,3,3 };

	int len = sizeof(a) / sizeof(int);

	int result = numMorethanHalf(&a, len);

	printf("%d\n", result);
}

主函数:

int main() {
	
	test1();
	test2();
	test3();
	test4();
	test5();
}

运行结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值