您的位置:首页 > 其它

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

2012-08-27 22:00 197 查看
题目:数组中有一个数组出现的次数超过了数组长度的一半,找出这个数字。

答:

#include "stdafx.h"
#include <iostream>

using namespace std;

//查找数组中超过出现次数超过一半的数字
int FindNumber(int arr[], int length)
{
if (NULL == arr || length <= 0)
{
return -1;
}
int nValue = arr[0];
int count = 1;
for (int i = 1; i < length; i++)
{
if (nValue == arr[i])
{
count++;
}
else
{
if (count == 0)
{
nValue = arr[i];
count = 1;
}
count--;
}
}
return nValue;
}

int _tmain(int argc, _TCHAR* argv[])
{
int arr[] = {1, 2, 3, 4, 5, 2, 2, 2, 2, 3, 2};
cout<<FindNumber(arr, sizeof(arr)/sizeof(arr[0]))<<endl;
return 0;
}


运行界面如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: