一、基于Partition函数的O(n)算法
数组中有一个数字出现的次数超过了数组长度的一半,如果把这个数组排序,那么排序之后位于数组中间的数字一定就是那个出现次数超过数组长度一半的数字。
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, start, end);
while (index != middle)
{
if (index > middle)
{
end = index - 1;
index = Partition(numbers, start, end);
}
else
{
start = index + 1;
index = Partition(numbers, start, end);
}
}
int result = numbers[middle];
if (!CheckMoreeThanHalf(numbers, length, result))// 检查是否result真的出现了一半以上
result = 0;
return result;
}
// A[low]为pivot
int Partition(int A[], int low, int high)
{
int len = high - low + 1;
if (len < 2)
return low;
int last = low;
for (int i = low + 1; i <= high; ++i)
{
if (A[i] < A[low])
swap(A, ++last, i);
}
swap(A, low, last);
return last;
}
二、根据数组特点找出O(n)的算法
由于数组中有个元素占到了一半以上,那么每次找出两个不同的数,然后“删除”它们,最后剩下的必定为target
int MoreThanHalfNum(int *numbers, 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;
}