【问题标题】:Where a Number Occur More than or equal to N/3 Times [duplicate]当一个数字出现超过或等于 N/3 次时 [重复]
【发布时间】:2023-02-02 14:08:26
【问题描述】:

查找在数组中出现超过 N/3 次的数字。不是N/2次?先看问题。

不使用摩尔算法。

【问题讨论】:

  • Boyer-Moore 算法。
  • 多数元素或元素至少出现 N/2 次 ?

标签: hash


【解决方案1】:

您将需要考虑最大值(最坏的情况是什么)。 除非你没有检查数组中的所有元素,否则 2 可以竞争到最后。

假设您有以下数组:

[1,2,3,1,2,2,1,2]

  • 当你在元素 4 时,1 是赢家,计数为 2。
  • 在元素 5 中,1 和 2 的表示相等。
  • 在元素 6 中,2 是赢家,计数为 3。
  • 等

基于此示例,您可以看到您需要遍历所有元素一次:O(n)

【讨论】:

    【解决方案2】:
    int majorityElement(int a[], int size){
            
            // your code here
            
            //Moore Voting Algorithm
            
            //Finding the candidate element
            int count = 1, res = 0;
            for(int i=1;i<size;i++){
                if(a[i]==a[res]) count++;
                else count--;
                if(count==0){
                    res = i;
                    count = 1;
                }
            }
            
            //Checking
            count = 0;
            for(int i=0;i<size;i++){
                if(a[i]==a[res]) count++;
                
            }
            return count>size/2? a[res]: -1;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-21
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-02
      相关资源
      最近更新 更多