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

时间:2022-12-01 11:02:52

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

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

过程:

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;
}

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

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;
}

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

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;
}

若要求不能修改数组,则采用第二种方法。