项目在阵列A中出现超过n / 2次

时间:2016-10-21 04:21:21

标签: algorithm

数组A[1 : : : n]由一些无限集S的项填充。(S不必是一组 数字和订单关系不需要在它上面定义。)用一个算法来描述一个算法 最坏情况时间复杂度,O(n)确定某个项目是否超出 数组A中n / 2次。不要忘记认为你的算法是正确的并且T(n) 确实是O(n)。

1 个答案:

答案 0 :(得分:1)

这是一个两步过程。

  1. 在数组中大部分时间获取元素。这个阶段将确保如果有多数元素,那么它将仅返回。
  2. 检查从上述步骤获得的元素是否为多数元素。
  3. 伪代码:

    findCandidate(a[], size)
    1.  Initialize index and count of majority element
         maj_index = 0, count = 1
    2.  Loop for i = 1 to size – 1
        (a) If a[maj_index] == a[i]
              count++
        (b) Else
            count--;
        (c) If count == 0
              maj_index = i;
              count = 1
    3.  Return a[maj_index]
    

    检查在步骤1中获得的元素是否为多数

    printMajority (a[], size)
    1.  Find the candidate for majority
    2.  If candidate is majority. i.e., appears more than n/2 times.
           Print the candidate
    3.  Else
           Print "NONE"
    

    reference

相关问题