[LeetCode] 229. Majority Element II

Medium

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.

Note: The algorithm should run in linear time and in O(1) space.

Example 1:

Input: [3,2,3]
Output: [3]

Example 2:

Input: [1,1,1,3,3,2,2,2]
Output: [1,2]


题目大意:
找到数列中出现次数大于n/3的数字

方法:
题目限制运行时间是线性的,所占空间为常数级。
使用摩尔投票的方法。每个数列中出现次数超过n/3的元素最多为两个(如果超过2个元素出现次数大于n/3:假设有3个元素出现次数超过n/3,那么3*time>n,(time>n/3),所以最多有两个元素出现次数超过n/3),那么先选出两个可能的目标元素,然后看这两个元素否都符合条件即可。
参考:https://www.cnblogs.com/grandyang/p/4606822.html
代码如下:
class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        if(nums.empty())return {};
        vector<int> res;
        int len=nums.size();
        int a=0,b=0,num_a=0,num_b=0;
        for(int num:nums){
            if(num==a)num_a++;
            else if(num==b)num_b++;
            else if(num_a==0){a=num;num_a=1;}
            else if(num_b==0){b=num;num_b=1;}
            else{num_a--,num_b--;}
        }
        num_a=num_b=0;
        for(int num:nums){
            if(num==a){num_a++;}
            else if(num==b){num_b++;}
        }
        if(num_a>len/3)res.push_back(a);
        if(num_b>len/3)res.push_back(b);
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/cff2121/p/11652925.html