給定一個長度為 n 的整數陣列,其中必定存在某個數字,出現次數超過 n/2。請找出這個數字。
如果一個數字佔據了半數以上的席位,那麼把整個陣列排序之後,站在正中央位置上的那個數,必然就是它。換句話說,答案就是統計學意義上的中位數。
既然目標只是「中間那一個」,我們其實不必付出完整排序的代價。受到快速排序中 partition 操作的啟發,可以反覆呼叫 partition,讓基準元素每一次都落到它最終該在的位置上:
每一輪只遞歸一側,平均時間複雜度可降到 O(n),比先排序再取中點更省。這種思路也被稱為「快速選擇」(quickselect)。
快速選擇只保證找到中位數,並不保證它真的出現超過一半。因此最後還要掃描一遍陣列做計數確認;若不成立,就回傳 0 表示輸入不合法。實務上還有一種更精簡的做法——摩爾投票法(Boyer–Moore Majority Vote),用 O(1) 的額外空間、單趟遍歷即可找出候選者,值得一併掌握。
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
// 生成 [min, max] 區間內的隨機數
int RandomInRange(int min, int max)
{
int random = rand() % (max - min + 1) + min;
return random;
}
// 交換兩個數
void Swap(int* num1, int* num2)
{
int temp = *num1;
*num1 = *num2;
*num2 = temp;
}
// 選取基準並把陣列切成兩段,回傳基準的最終位置
int Partition(int data[], int length, int start, int end)
{
if (data == NULL || length <= 0 || start < 0 || end >= length)
exit(1);
int index = RandomInRange(start, end);
Swap(&data[index], &data[end]);
int small = start - 1;
for (index = start; index < end; ++index)
{
if (data[index] < data[end])
{
++small;
if (small != index)
Swap(&data[index], &data[small]);
}
}
++small;
Swap(&data[small], &data[end]);
return small;
}
bool g_bInputInvalid = false;
// 檢查輸入是否有效
bool CheckInvalidArray(int* numbers, int length)
{
g_bInputInvalid = false;
if (numbers == NULL && length <= 0)
g_bInputInvalid = true;
return g_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)
{
g_bInputInvalid = true;
isMoreThanHalf = false;
}
return isMoreThanHalf;
}
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))
result = 0;
return result;
}
int main()
{
int numbers[] = {1, 2, 3, 2, 2, 2, 5, 4, 2};
int length = sizeof(numbers) / sizeof(int);
printf("Test for solution: ");
int result = MoreThanHalfNum(numbers, length);
if (g_bInputInvalid == false)
printf("%d \n", result);
else
printf("Failed.\n");
}