【刷题-LeetCode】229. Majority Element II

  1. 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]

摩尔投票法

回顾求解超过一半的数字。假设超过一半的数字是x,剩下数字的集合记做是Y(\(|Y|<\frac{n}{2}\)),对于任意的\(y_i\in Y\),都能有一个x和其配对,最后还会剩下一个x或者刚好配对完。具体实现为:

实现的算法从第一个数开始扫描整个数组,有两个变量(参考第一答题者的变量名)major和count。其实这两个变量想表达的是一个“隐形的数组”array,array存储的是“当前暂时无法删除的数字”,我们先不要管major和count,只考虑这个array,同时再维护一个结果数组result,result里面存储的是每次删除一对元素之后的当前结果。[]

实现的算法从第一个数开始扫描整个数组,有两个变量(参考第一答题者的变量名)major和count。其实这两个变量想表达的是一个“隐形的数组”array,array存储的是“当前暂时无法删除的数字”,我们先不要管major和count,只考虑这个array,同时再维护一个结果数组result,result里面存储的是每次删除一对元素之后的当前结果。[https://www.zhihu.com/question/49973163/answer/235921864]

对于超过1/3的数字,必然最多有2两个。思路与求1/2的类似

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        int m, n, cnt_m = 0, cnt_n = 0;
        for(int x : nums){
            if(m == x){
                cnt_m++;
            }else if(n == x){
                cnt_n++;
            }else if(cnt_m == 0){
                cnt_m = 1;
                m = x;
            }else if(cnt_n == 0){
                cnt_n = 1;
                n = x;
            }else{
                cnt_m--;
                cnt_n--;
            }
        }
        cnt_m = 0, cnt_n = 0;
        for(int x: nums){
            if(x == m)cnt_m++;
            else if(x == n)cnt_n++;
        }
        vector<int>res;
        if(cnt_m > nums.size() / 3)res.push_back(m);
        if(cnt_n > nums.size() / 3)res.push_back(n);
        return res;
    }
};
posted @ 2020-07-21 09:53  十三w~w  阅读(93)  评论(0编辑  收藏  举报