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

327人阅读 评论(0)

int MoreThanHalfNum(int* numbers, int length)
{
if (CheckInvalidArray(numbers, length))
return 0;
int middle = length >> 1;
int start = 0;
int end = length - 1;
int index = Partition(numbers, length, start, end);
while (index != middle)
{
if (index > middle)
{
end = index - 1;
index = Partition(numbers, length, start, end);
}
else
{
start = index + 1;
index = Partition(numbers, length, start, end);
}
}
int result = numbers[middle];
if (!CheckMoreThanHalf(numbers, length, result))
return 0;
return result;
}

bool q_bInputInvalid = false;
bool CheckInvalidArray(int* numbers, int length)
{
q_bInputInvalid = false;
if (numbers == NULL&&length <= 0)
q_bInputInvalid = true;
return q_bInputInvalid;
}
bool CheckMoreThanHalf(int *numbers, int length, int number)
{
int times = 0;
for (int i = 0; i < length; ++i)
{
if (numbers[i] == number)
times++;
}
bool isMoreThanHalf = true;
if (times * 2 <= length)
{
q_bInputInvalid = true;
isMoreThanHalf = false;
}
return isMoreThanHalf;
}

int MoreThanHalfNumber(int* numberes, int length)
{
if (CheckInvalidArray(numbers, length))
return 0;
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--;
}
if (!CheckMoreThanHalf(numbers, length, result))
result = 0;
return result;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：168344次
• 积分：6269
• 等级：
• 排名：第4063名
• 原创：479篇
• 转载：2篇
• 译文：1篇
• 评论：3条
阅读排行
评论排行
最新评论