主元素 III-LintCode

204 篇文章 0 订阅

给定一个整型数组,找到主元素,它在数组中的出现次数严格大于数组元素个数的1/k。

注意事项
数组中只有唯一的主元素

您在真实的面试中是否遇到过这个题? Yes
样例
给出数组 [3,1,2,3,2,3,3,4,4,4] ,和 k = 3,返回 3

挑战
要求时间复杂度为O(n),空间复杂度为O(k)

#ifndef C48_H
#define C48_H
#include<vector>
#include<iostream>
#include<map>
using namespace std;
class Solution {
public:
    int majorityNumber(vector<int> nums, int k) {
        map<int, int> m;
        int size = nums.size();
        //找到k个不同的数就抵消
        for (int i = 0; i < size; ++i)
        {
            if (m.size() < k)
            {
                m[nums[i]]++;           
            }
            else
            {
                if (m.find(nums[i]) != m.end())
                    m[nums[i]]++;
                else
                {
                    for (auto &c : m)
                    {
                        c.second--;
                    }
                    for (auto it = m.begin(); it != m.end();)
                    {
                        if (it->second <= 0)
                        {
                            m.erase(it++);
                        }
                        else
                        {
                            it++;
                        }
                    }
                }
            }
        }
        for (auto &c : m)
        {
            c.second = 0;
        }
        for (auto t : nums)
        {
            if (m.find(t) != m.end())
                m[t]++;
        }
        int res = 0;
        int cnt = INT_MIN;
        for (auto c : m)
        {
            if (cnt < c.second)
            {
                cnt = c.second;
                res = c.first;
            }
        }
        return res;
    }
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值