zoukankan      html  css  js  c++  java
  • 【刷题-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_iin 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;
        }
    };
    
  • 相关阅读:
    Codeforces 1355 D. Game With Array
    Codeforces 1355 C. Count Triangles
    Codeforces Round #641 (Div. 2)
    Codeforces 1345 D
    hdu6787(骰子+往回推的传输带问通过方案,dp)
    hdu6745(渐减1过程的最多互质对数,dp)
    D Points Construction Problem(思维构造,等周定理)
    Codeforces Round #658 (Div. 2)D(01背包)
    Codeforces Round #655 (Div. 2)E(矩阵范围dp)
    hdu4622([u,v]内有多少个子串)
  • 原文地址:https://www.cnblogs.com/vinnson/p/13353344.html
Copyright © 2011-2022 走看看