229. Majority Element II

问题描述:

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]

 

解题思路:

由于要求我们用O(1)的空间复杂度,那我们可以类比169. Majority Element

使用摩尔投票法。

出现个数大于n/3最多有两个数字:将数组等份分成3份,若要大于n/3,那么可以有两份分别为一个数字,同时再从第三份里取至少一个数字。

所以我们可以用摩尔投票法先找到这两个,然后再循环一遍确认个数是否满足条件

 

代码:

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> ret;
        int can1 = 0, can2 = 0;
        int cnt1 = 0, cnt2 = 0;
        for(int n:nums){
            if(n == can1) cnt1++;
            else if(n == can2) cnt2++;
            else if(cnt1 == 0) {
                can1 = n;
                cnt1 = 1;
            }else if(cnt2 == 0){
                can2 = n;
                cnt2 = 1;
            }else{
                cnt1--;
                cnt2--;
            }
        }
        cnt1 = 0;
        cnt2 = 0;
        for(int n : nums){
            if(n == can1)cnt1++;
            else if(n == can2) cnt2++;
        }
        int stdNum = nums.size()/3;
        if(cnt1 > stdNum) ret.push_back(can1);
        if(cnt2 > stdNum) ret.push_back(can2);
        return ret;
    }
};

 

posted @ 2018-06-26 06:02  妖域大都督  阅读(86)  评论(0编辑  收藏  举报