一、问题 序列A[1..n]中是存在主元素? 若有请找出来。 二、算法1——穷举法 三、算法2——利用排序算法 四、算法3——利用找中值元素的算法 五、算法4
注: A 中主元素是指在A中出现次数多于? n/2?次的元素。
1.算法基本思想
如果删去原序列中的两个不同元素,则原序列中的主元素仍然在剩下的序列中 。
2.算法 MAJORITY
Input:A array A[1..n] of n elements.
Output: The majority element if it exists;otherwise none.
1. c←candidate(1)
2. count←0
3. for j←1 to n
4. if A[j]=c then count←count+1
5. end for
6. if count>[n/2] then return c
7. else return none
Procedure candidate(m)
1. j←m; c←A[m]; count←1
2. while j<n and count>0
3. j←j+1
4. if A[j]=c then count←count+1
5. else count←count-1
6. end while
7. if j=n then return c {See Exercises 5.31 and 5.32}
8. else return candidate(j+1)
找主元素
最新推荐文章于 2022-10-12 21:54:25 发布
时间复杂度:Q(n2)
时间复杂度:Q(nlogn)
时间复杂度:Q(n)
Algorithm MAJORITY