LeetCode 229. Majority Element II

LeetCode 229. Majority Element II

原题目:

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

题目翻译:

给出一个大小为n的整型数组,找到所有出现次数大于 ⌊ n/3 ⌋ 次的元素。算法必须在线性时间内运行,并且空间复杂度为O(1)。

题目理解:

1) 如果没有空间的限制,直接用hash表,求出所有元素的次数即可得到答案。但是题目要求是O(1)的空间,因此得考虑别的方法;
2) 题目给出了一个Hint: How many majority elements could it possibly have? 因此可以考虑到n个元素中次数大于 ⌊ n/3 ⌋ 次的元素个数最多为2个。结合之前的LeetCode 169. Majority Element中采用的Boyer–Moore majority vote algorithm,就知道该怎么做了。

步骤:

1) 在第一次遍历中,用两个变量first, second保存频次最高的2个元素,用两个计数器countf, counts记录first和second抵消其他元素后的频次;
2) 由于遍历完之后,最高频次的2个元素可能次数没有大于 ⌊ n/3 ⌋ 次,如1,2,3,4,5,6,7这个序列,因此需要进行第二次遍历,将两个计数器countf, counts置0,得到这2个元素的真正频次;
3) 满足大于 ⌊ n/3 ⌋ 次的元素就放入结果向量中。

备注:

算法原理可以参见Boyer–Moore majority vote algorithm
还有一个比较好理解的展示效果A Linear Time Majority Vote Algorithm

AC代码如下:(C++, 13ms)

class Solution {
public:
    vector<int> majorityElement(vector<int>& nums) {
        vector<int> ans;
        if (nums.empty())   return ans;
        if (nums.size() == 1) {
            ans.push_back(nums[0]);
            return ans;
        }

        int first = nums[0];
        int second = nums[0];
        int countf = 1;
        int counts = 0;

        /* 找出频次最高的两个元素 */
        for (int i = 1; i < nums.size(); i++) {
            if (nums[i] == first) {
                countf++;
            }
            else if (nums[i] == second) {
                counts++;
            }
            else if (countf == 0) {
                first = nums[i];
                countf = 1;
            }
            else if (counts == 0) {
                second = nums[i];
                counts = 1;
            }
            else {
                countf--;
                counts--;
            }
        }

        /* 找出次数大于⌊ n/3 ⌋次的元素 */
        countf = counts = 0;
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] == first)           countf++;
            else if (nums[i] == second)     counts++;
        }

        if (countf > nums.size() / 3)   ans.push_back(first);
        if (counts > nums.size() / 3)   ans.push_back(second);

        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值