• [LeetCode] 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]

    n/3 times说明这样的数至多存在2个。

    所以使用两个数n1,n2表示候选的数字,c1,c2表示这两个数出现的次数。

    遍历数组,记当前数组为num,如果num与n1,n2其一相等,则对应的c1或c2加一。

    如果num与n1和n2都不等,此时如果c1或c2其一为0,则令对应的候选数为num,并令其加一,

    否则c1和c2各自减一,

    最后再统计一次候选数字出现的次数是否大于n/3

    class Solution {
    public:
        vector<int> majorityElement(vector<int>& nums) {
            vector<int> res;
            if (nums.empty())
                return res;
            int n1 = nums[0], n2 = 0;
            int c1 = 1, c2 = 0;
            for (int i = 1; i < nums.size(); ++i)
            {
                if (nums[i] == n1)
                    c1++;
                else if (nums[i] == n2)
                    c2++;
                else
                {
                    if (c1 == 0)
                    {
                        n1 = nums[i];
                        c1 = 1;
                    }
                    else if (c2 == 0)
                    {
                        n2 = nums[i];
                        c2 = 1;
                    }
                    else
                    {
                        c1--;
                        c2--;
                    }
                }
            }
            c1 = 0, c2 = 0;
            for (auto& num : nums)
            {
                if (num == n1)
                    c1++;
                else if (num == n2)
                    c2++;
            }
            if (c1 > nums.size() / 3)
                res.push_back(n1);
            if (c2 > nums.size() / 3 && n1 != n2)
                res.push_back(n2);
            return res;
        }
    };
    // 12 ms
  • 相关阅读:
    c++ new 堆 栈
    c++ int 负数 补码 隐式类型转换
    python json 序列化
    %pylab ipython 中文
    matplotlib中什么是后端
    IPython 4.0发布:Jupyter和IPython分离后的首个版本
    ipython
    python 类
    python 高级特性
    windows网络模型
  • 原文地址:https://www.cnblogs.com/immjc/p/9157815.html
Copyright © 2020-2023  润新知