查找数组中出现次数超过一半的数
解法一 对数组运用快排,取 n/2处的数为超过一半的数
解法二 用空间换时间,以散列表中存储出现过的数据,和出现的次数
解法三 每次 删除数组中两个不同的数,剩下的那个数就是出现次数超过一半的数
解法四 保存两个值 ,candidate用来保存数组中遍历的某个数,nTimes 用来保存遍历到的数出现的次数
int findOneNumber(int *a,int n)
{
int candidate, nTimes;
candidate = 0;
nTimes = 1;
for (int i = 1; i < n; i++)
{
if (nTimes == 0)
{
candidate = i;
nTimes = 1;
}
else
{
if (a[candidate] == a[i])
{
nTimes++;
}
else
{
nTimes--;
}
}
}
return candidate;
}
int main()
{
int a[] = { 0,1,2,1,1 };
int index = findOneNumber(a, 5);
cout<<a[index];
system("pause");
return 0;
}