一位讲师在课堂上提出了这个问题:[问题]
n 个整数的序列存储在数组 A[1..n] 中。如果一个整数 a 在 A 中出现超过 n/2 次,则称为多数。
可以设计一个 O(n) 算法来根据以下观察找到多数:如果原始序列中的两个不同元素被删除,则原始序列中的多数仍然是新序列中的多数。使用这种观察或其他方式,编写编程代码以在 O(n) 时间内找到大多数(如果存在)。
接受此解决方案的[解决方案]
int findCandidate(int[] a)
{
int maj_index = 0;
int count = 1;
for (int i=1;i<a.length;i++)
{
if (a[maj_index] == a[i])
count++;
else
count--;
if (count == 0)
{
maj_index =i;
count++;
}
}
return a[maj_index];
}
int findMajority(int[] a)
{
int c = findCandidate(a);
int count = 0;
for (int i=0;i<a.length;i++)
if (a[i] == c) count++;
if (count > n/2) return c;
return -1;//just a marker - no majority found
}
我看不出所提供的解决方案如何是动态解决方案。而且我看不出他是如何根据措辞提取代码的。