假设有一个数组,其中含有N个非负元素,求其中是否存在一个元素其元素个数大于等于N/2。
分析:看到这个问题最先想到的是暴力算法,将数组在O(NlogN)的时间内进行排序,然后扫描一次数组就知道是否存在满足条件的元素了。
算法实现:
int Majority_Vote_Sort(const int* a, const int n)
{
?sort(a,n);
?int count=0;
?int max = 0;
?int now = a[0];
?int res = a[0];
?for(int i=1; i?{
? if(a[i] == now)
? {
? ?count++;
? }
? else
? {
? ?if(count > max)
? ?{
? ? max = count;
? ? res = now;
? ?}
? ?now = a[i];
? ?count = 0;
? }
?}
?return max;
?//return res;
}
上述算法可以在O(logN)的时间内找到满足条件的元素,但是仔细观察发现,算法中对数组的排序似乎是多余的,为此可以在算法排序处进行一定的改进便可以得到更加快速的算法。
学过hash表的同学看到这个问题通常容易想到使用一个定义一个数组count,其中数组的角标为原来数组的元素值,count数组的元素值代表了这个角标元素出现的次数,由此可以在扫面一遍数组的情况下获得原数组中各个元素的个数,从而解决此题。也可以利用hash表来替代count数组,这样做的话算法的鲁棒性会更好。
算法实现
int Majority_Vote(const int* a, const int n)
{
?int* res = new int[n];
?for(int i=0; i? res[i] = 0;
?for(int i=0; i? res[a[i]]++;
?int max = res[0];
?for(int i=1; i?{
? if(max < res[i])
? ?max = res[i];
?}
?delete[] res;
?return max;
}
上述算法在时间复杂度上做到了最优,但是却花费了额外的空间复杂度,为此,查阅文献的时候发现了一个很神奇的方法A Fast Majority Vote Algorithm,此方法只需在常数空间复杂度上就可以实现上述算法的功能。
神奇算法的思路:(存在一个计数器count和一个临时存储当前元素的变量now)
算法实现
int Majority_Vote_update(const int* a, const int n)
{
?struct item
?{
? int now;
? int count;
?};
?item* t = new item;
?t->count = 0;
?for(int i=0; i?{
? if(t->count == 0)
? {
? ?t->now = i;
? ?t->count = 1;
? }
? else
? {
? ?if(t->now == a[i])
? ? t->count++;
? ?else
? ? t->count--;
? }
?}
?int res=0;
?for(int i=0; i?{
? if(t->now == a[i])
? ?res++;
?}
?if(res >= n+1/2)
? return res;
?else
? return -1;
}
上述算法只需在常数的额外空间的条件下就可以在常数的时间内判断并找出符合条件的元素。
此文仅供参考,若要挖掘算法的理论基础,请点击A Fast Majority Vote Algorithm