美文网首页
229. Majority Element II

229. Majority Element II

作者: 叶孤陈 | 来源:发表于2017-07-24 14:58 被阅读0次

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

分析:
本题是169.Majority Element的扩展,需要两次遍历,第一次遍历选出两个候选众数,第二次求出两个众数的出现次数,最后返回出现大雨n/3的众数。

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
       int num = nums.size();
       int major0 = 0, major1 = 0, count0 = 0, count1 = 0;
       for(int i = 0; i < num; ++i)
       {
           if(major0 == nums[i])
                count0++;
           else if(major1 == nums[i])
                count1++;
           else if(count0 == 0) 
           {
               major0 = nums[i];
               count0++;
           }else if(count1 == 0) 
           {
               major1 = nums[i];
               count1++;
           }else
           {
               count0--;
               count1--;
           }
       }
        
       count0 = 0, count1 = 0; //出现次数重新置0,第二次遍历重新求出现次数
       for(int i = 0; i < num;++i)
       {
           if(nums[i] == major0) count0++;
           else if(nums[i] == major1) count1++;
       }
     
       vector<int> ret;
       if(count0 > num/3) ret.push_back(major0);
       if(count1 > num/3) ret.push_back(major1);
        
       return ret;
        
    }
};

相关文章

  • II Boyer-Moore Majority Vote Alg

    229. Majority Element II Given an integer array of size n...

  • 229. Majority Element II

    先排序 然后顺序扫描,需要注意边缘,代码如下: 但是这道题目限制了时间是限行时间空间是o(1),因此,既不能使用排...

  • 229. Majority Element II

    Given an integer array of size n, find all elements that ...

  • 229. Majority Element II

    题目 题目很简短,给定一个包含n个数字的数组,找出所有出现次数超过 ⌊ n/3 ⌋ 次的数。要求O(n)时间复杂度...

  • 229. Majority Element II

    思路就是三个三个删,如何描述是三个三个删的关键是两个count要描述好。之前没仔细写,count应该有四种case...

  • 229. Majority Element II

    Question Given an integer array of size n, find all eleme...

  • 229. Majority Element II

    https://leetcode.com/problems/majority-element-ii/ 给定一个数组...

  • 229. Majority Element II

    给定一个大小为 n 的整数数组,找出其中所有出现超过 ⌊ n/3 ⌋ 次的元素。 摩尔投票法 大于 n/3 的数最...

  • 229. Majority Element II (M)

    Given an integer array of size n, find all elements that ...

  • Majority Element II

    Majority Element II 今天是一到有关数学计算的题目,是Majority Element(回复01...

网友评论

      本文标题:229. Majority Element II

      本文链接:https://www.haomeiwen.com/subject/zysbkxtx.html