数组中出现次数超过一半的数字

//1,2,3,2,2,2,5,4,2   len=9  return 2;出现次数超过一半
//元素在数组中出现的次数STL
//各种排序
void BubleSort(int num[],int len)
{
	int i, j,temp;
	for (i = 0; i < len; i++)
	{
		for (j = 0; j < len -1- i; j++)
		{
			if (num[j]>num[j + 1])
			{
				temp = num[j];
				num[j] = num[j + 1];
				num[j + 1] = temp;
			}
		}
	}
}
int partition(int num[], int first, int end)
{
	int i, j,temp;
	i = first;
	j = end;
	temp = num[i];
	while (i < j)
	{
		while (i<j && num[j]>temp)
		{
			j--;
		}
		if (i < j)
		{
			num[i++] = num[j];
		}
		while (i < j && num[i] < temp)
		{
			i++;
		}
		if (i < j)
		{
			num[j--] = num[i];
		}
	}
	num[i] = temp;
	return i;
		
}
void QuickSort(int num[],int first,int end)
{
	int index;
	if (first < end)
	{
		index = partition(num, first, end);
		QuickSort(num, first, index - 1);
		QuickSort(num, index + 1, end);
	}
}
bool istrue(int num[],int len, int index)
{
	int times, i;
	times = 0;
	for (i = 0; i < len; i++)
	{
		if (num[i] == index)
		{
			times++;
		}
	}
	if (times * 2 <= len)
		return false;
	else
		return true;
}
//Find the num which was more than the half in the array
void MoreThanHalf(int num[], int len,int first,int end)//利用partition函数找到中位数
{
	if (num == NULL || len < 0)
		return;
	int middle = len >> 1;
	int index;
	index = partition(num, first, end);
	while (index != middle)
	{
		if (index < middle)
		{
			first = index + 1;
			index = partition(num, first, end);
		}
		else
		{
			end = index - 1;
			index = partition(num, first,end);
		}
	}
	int result;
	result = num[index];
	if (istrue(num, len, result))
	{
		cout<< result;
	}
	else
	{
		cout << "Donot have!" << endl;
	}
}

/*<span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">数组中有个数字出现的次数超过了数组长度的一半。也就是说,有个数字出现的次数比其他所有数字出现次数的和还要多。</span><br style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;" /><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">    因此我们可以考虑在遍历数组的时候保存两个值:一个是数组中的一个数字,一个是次数。当我们遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则次数加1。 如果下一个数字和我们之前保存的数字不同,则次数减1。如果次数为零,我们需要保存下一个数字,并把次数重新设为1。  */</span>
int FindHalf(int *a, int n)
{
	int candidate;
	int times, i;
	for (i = times = 0; i < n; i++)
	{
		if (times == 0)
		{
			candidate = a[i];
			times = 1;
		}
		else
		{
			if (candidate == a[i])
			{
				times++;
			}
			else
			{
				times--;
			}
		}
	}
	return candidate;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值