`
xitonga
  • 浏览: 584089 次
文章分类
社区版块
存档分类
最新评论

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

 
阅读更多
/*****************************************************************
题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。
例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。由于数字2在数组中出现
了5次,超过数组长度的一半,因此输出2。
*****************************************************************/\
#include<stdio.h>
#include<iostream>

void swap(int* a, int* b)
{
	int nTemp = *a;
	*a = *b;
	*b = nTemp;
}
int partition(int* numbers, int start, int end)
{
	int standard = numbers[end];
	int small = start - 1;
	for(int i = start; i<end; ++i)
	{
		if(numbers[i]<standard)
		{
			++small;
			if(i != small)
				swap(&numbers[i],&numbers[small]);
		}
	}
	++small;
	swap(&numbers[small],&numbers[end]);
	return small;
}
//方法一
//找排序后的中卫数,可以借鉴快速排序思想寻找中位数,复杂度为O(N)
int moreThanHalfNumber(int* numbers, int length)
{	
	//无效输入
	if(numbers == NULL || length <= 0)
		throw new std::exception("Invalid input!\n");

	int middle = length >> 1;
	int start = 0;
	int end = length-1;
	int index = partition(numbers,start,end);
	while(index != middle)
	{
		if(index<middle)
		{
			start = index+1;
			index = partition(numbers,start,end);
		}
		else
		{
			end = index-1;
			index = partition(numbers,start,end);
		}
	}
	
	int result = numbers[middle];
	
	int times = 0;
	for(int i=0; i<length; ++i)
	{
		if(numbers[i] == result)
			++times;
	}
	if(times * 2 <= length)
		throw new std::exception("Invalid input!\n");
	else
		return result;
}
//方法2
//遍历数组的时候保存两个值:一个是数组中的数字,一个是次数。当我们
//遍历到下一个数字的时候,如果下一个数字和我们之前保存的数字相同,则、
//次数加1;如果下一个数字和我们之前保存的数字不同,则次数减1.如果次数
//为0,我们需要保存下一个数字,并把次数设为1.由于我们要找的数字出现的
//次数比其他所有数字出现的次数之和还多,那么要找的数字肯定是最后一次把
//次数设为1时对应的数字。
//复杂度为O(N)
int moreThanHalfNumber2(int* numbers, int length)
{
	//无效输入
	if(numbers == NULL || length <= 0)
		throw new std::exception("Invalid input!\n");

	int result = numbers[0];
	int times = 1;
	for(int i=1; i<length; ++i)
	{
		if(times == 0)
		{
			result = numbers[i];
			times = 1;
		}
		else if(numbers[i] == result)
		{
			++times;
		}
		else
			--times;
	}
	
	times = 0;
	for(int i=0; i<length; ++i)
	{
		if(numbers[i] == result)
			++times;
	}
	if(times * 2 <= length)
		throw new std::exception("Invalid input!\n");
	else
		return result;
}
void test()
{
	const int length = 9;
	int numbers[length] = {1,2,3,2,2,2,5,4,2};
	printf("%d\n",moreThanHalfNumber2(numbers,length));
}
int main()
{
	test();
	return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics